Cover

JavaScript for the C# Guy: Function Overloads

March 10, 2012
No Comments.

I’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() {
  alert(arguments.length);
  alert(arguments[0]);
}

You can play with this functionality in this JSFiddle:

What do you think?