Skip navigation

Tag Archives: function overloading


Let us take the following function

function add(x, y) {
    var total = x + y;
    return total;
}

Call it..

add();  // 1) answer: NaN
add(2,3);  // 2) answer: 5
add(3,3,5);  // 3) answer: 6

You expect second call but what about first and third. To understand this, you need to know about argument property. Again consider the code

function add(x, y) {
    alert(arguments.length);
    var total = x + y;
    return total;
}

You will be alerted with 0, 2, 3 respectively. By the by, the arguments object will be available within all function body. Refer https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments

There is no need to pass exactly the same number of parameters as defined while calling the function. We can check how many parameters are passed within the function itself using arguments.length property.

mmm…. What is the practical use of this feature

function add(x, y) {
  var total = 0;
  for (var i = 1; i < arguments.length; i++)
    total += arguments[i];
    return total;
}

OOPs guys some times call this as function overloading. But the word “function overloading” is not used in the same meaning as used in traditional languages like Java, C#, etc.

Hope this will help…

Also check another post on the same topic at https://vkanakaraj.wordpress.com/2009/02/27/function-parameter-shock/

My discussion on stack over flow.

Advertisements

 

function add(x, y) {
    var total = x + y;
    return total;
}
  • The return statement is optional. 
  • If no return statement is used (or an empty return with no value), JavaScript returns undefined.
  • The named parameters turn out to be more like guidelines than anything else. You can call a function without passing the parameters it expects, in which case they will be set to undefined.
  • alert(add());

We can just call without any parameters

add();

in which case it will return NaN because you can’t add undefined values.

Even you can call 

add(2,3,4,5);

in which case it will return 5, ignoring 4 and 5.

OOPs guys will call it as FUNCTION OVERLOADING.