What is the Rest Parameter in a Function?

Learn full article on Infragistics blog

A JavaScript function can take any number of parameters. Unlike other languages like C# and Java, you can pass any number of parameters while calling a JavaScript function. JavaScript functions allows unknown number of function parameters. Before ECMAScript 6, JavaScript had arguments variable to access these unknown or variable number of parameters, which is an array-like object but not an array. Consider this code listing to understand the argumentsvariable:


function add(){
var result = 0;
for(let i=0;i<arguments.length;i++){
result = result + arguments[i];
}
return result;
}
var r = add(6,9,3,2);
console.log(r);
var t = add(7,56,9);
console.log(t);

view raw

letfunction1.js

hosted with ❤ by GitHub

As you see, that arguments object is used to access unknown or variable function parameters.  Even though arguments uses length property and square brackets, it is not a real JavaScript array. You cannot use other JavaScript array methods like pop, push, slice etc. with the arguments object.  Some of the problems in using arguments are:

  • JavaScript function arguments object is not a real JavaScript array; therefore, you cannot use other array methods like pop, push, slice, etc. with it
  • It is difficult to access arguments object of outer function in an inner function. To use it, you need to assign outer function arguments object in a variable, and then use it in an inner function
  • If you want to use arguments object as an array, then you need to convert it manually using Aarry.prototype.slice

ECMAScript 6 introduces a new feature, Rest Parameters, which represents an unknown number of parameters as an array in a function. It not only represents extra parameters as an array, it also solves many of the problems of the arguments object.  Let us rewrite the above add function using the rest parameters.


function add(…theArgs){
var result = 0;
for(let i=0;i<theArgs.length;i++){
result = result + theArgs[i];
}
return result;
}
var r = add(6,9,3,2);
console.log(r);
var t = add(7,56,9);
console.log(t);

view raw

letfunction2.js

hosted with ❤ by GitHub

Learn full article on Infragistics blog

Leave a comment

Create a website or blog at WordPress.com