Method overloading in Javascript

You're just erasing the variable somefunction with each new declaration.

This is equivalent to

   window.somefunction = function(...
   window.somefunction = function(...
   window.somefunction = function(...

Javascript doesn't offer method overloading.

The proper way is either :

  • to define the third function and to test what parameters are defined
  • to pass only one object containing the parameters (which isn't really different but is cleaner)

JavaScript does not support method overloading (as in Java or similiar), your third function overwrites the previous declarations.

Instead, it supports variable arguments via the arguments object. You could do

function somefunction(a, b) {
    if (arguments.length == 0) { // a, b are undefined
        // 1st body
    } else if (arguments.length == 1) { // b is undefined
        // 2nd body
    } else if (arguments.length == 2) { // both have values
        // 3rd body
    } // else throw new SyntaxError?
}

You also could just check for typeof a == "undefined" etc, this would allow calling somefunction(undefined), where arguments.length is 1. This might allow easer calling with various parameters, e.g. when you have possibly-empty variables.


JS will pass undefined to any parameters which are not provided. If you want something like overloading, you'll need to do something similar to the code below:

function someFunction(a, b) {
    if (typeof a === 'undefined') {
        // Do the 0-parameter logic
    } else if (typeof b === 'undefined') {
        // Do the 1-parameter logic
    } else {
        // Do the 2-parameter logic
    }
}