JavaScript for the C# Guy: Function Overloads

dreamstime_1087355089A3Ib17I’ve been writing a lot of JavaScript lately. As a C# guy, I noticed that try and take my knowledge from my time in C# (and C++ and even a little Java) and try to apply it. They are curly braces after all…but alas it doesn’t always work. I’ll learn my lesson one day ;) (though I doubt it).

Lesson for today? Function overloads. Coming from that world I wrote simple code like this:

function myFunction(one) {

function myFunction(one, two) {

myFunction("a parameter");

Naively I assumed the calling to myFunction will execute the first function but of course it doesn’t work that way. The execution of the myFunction with one parameter calls the second function. Why? The 2nd function declaration replaces the first with the same name. So that no matter what you call as parameters, the 2nd function will be called. This is because functions in JavaScript do not have signatures, just names. In fact, I could have written the function without any parameters:

function myFunction() {

If the function has no parameters, how do I get at the parameter(s) that were passed? Simple, within the body of the function, there is always a variable called ‘arguments’ that has the list of arguments passed to the function:

function myFunction() {

You can play with this functionality in this JSFiddle:

What do you think?

Shawn Wildermuth
Author, Teacher, and Coach

My Courses

Wilder Minds Training
Vue.js by Example
Bootstrap 4 by Example
Intro to Font Awesome 5 (Free Course)
Designing RESTful Web APIs (new)
Building an API with ASP.NET Web API
Building an API with ASP.NET Core
Building a Web App with ASP.NET Core, MVC6, EF Core, Bootstrap and Angular
Less: Getting Started

Application Name WilderBlog Environment Name Production
Application Ver v4.0.30319 Runtime Framework x86
App Path D:\home\site\wwwroot\ Runtime Version .NET Core 3.0.0
Operating System Microsoft Windows 10.0.14393 Runtime Arch X86