Skip navigation

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

One Comment

  1. The right way to do it,

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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: