Passing and Accessing Variable Number of Parameters in Function

This article is related to passing and accessing a variable number of parameters in a function/method. As we know in languages like C# we need to pass an exact number of parameters to call a method as determined by the method definition (except optional parameters). JavaScript has provided us a way to pass a greater or fewer number of parameters than in the function definition when calling a function and it will not complain. I will use an example to explain it.

  1. function Sum(num1, num2) {  
  2.             return num1 + num2;  
  3.  } 

The Sum function takes two numbers and returns the sum of the numbers passed.

This function is showing static behavior, in other words we can get the sum of only two numbers. But what if we want a sum of numbers entered by users. A user can pass as many parameters as he/she wants. In that case this function will not fulfill our requirements. Example:

>Sum(); // Expected : 0; Actual : NaN; No Error

>Sum(1); // Expected : 1; Actual : NaN; No Error

>Sum(1,2); // Expected : 3; Actual : 3

>Sum(1,2,4); // Expected : 7; Actual : 3; No Error

Note: The receding lines of code in GREEN passed the user's expectation and in RED failed the expectation.

We do not know how many numbers the user wants to sum, in other words we do not know how many parameters the user will pass to the function.

Now I made changes to the definition of the Sum function to behave properly for the new user requirements.

  1. function Sum() {  
  2.         var sum = 0;  
  3.         for (var i = 0; i < arguments.length; i++) {  
  4.             sum = sum + arguments[i];  
  5.         }  
  6.         return sum;  
  7.  } 

Now the function is able to fulfill the user's requirements to get a sum of any numbers.

>Sum(); // Expected : 0; Actual : 0

>Sum(1); // Expected : 1; Actual : 1

>Sum(1,2); // Expected : 3; Actual : 3

>Sum(1,2,4); // Expected : 7; Actual : 7

arguments: when I included the user's requirements, it was the savior (please see the Sum() function definition above). The arguments word is a reserved word in JavaScript. It is a special variable. Its scope is the current function. The individual parameters are accessed via square brackets ([]) and the total number of parameters passed via arguments.length. arguments look like an Array, but it has none of the array methods.

Sum(); // arguments.length : 0; arguments[0]: undefined

Sum(1,2);// arguments.length : 2; arguments[0] : 1

Conclusion

  •  JavaScript will not complain when a greater or fewer number of parameters are passed than in the function definition.
  • To check how many parameters were passed to the function: arguments.length
  • To access the nth parameter's value: variable = arguments[n-1];
  • To set the nth parameter's value: arguments[n-1] = some value;

I hope this was helpful for you.

Up Next
    Ebook Download
    View all
    Learn
    View all