Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Easy JavaScript Part 2: What Is the Rest Parameter in a Function?

DZone's Guide to

Easy JavaScript Part 2: What Is the Rest Parameter in a Function?

If you're new to JavaScript or just looking for a refresher, this series is for you. Read on to see how to make you JavaScript code Dry using the rest parameter.

· Web Dev Zone
Free Resource

Get deep insight into Node.js applications with real-time metrics, CPU profiling, and heap snapshots with N|Solid from NodeSource. Learn more.

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 allow an unknown number of function parameters. Before ECMAScript 6, JavaScript had a variable to access these unknown or variable numbers of parameters, which is an array-like object but not an array. Consider this code to understand the arguments variable:

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);

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:

  • The 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 an arguments object of an outer function in an inner function. To use it, you need to assign the arguments function of the outer function in a variable, and then use it in an inner function.
  • If you want to use the 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);

You can define a rest parameter as ...theArgs or ...args. If the last-named function parameter is prefixed with ... (three dots), it becomes the rest parameter of the function. JavaScript functions' rest parameters are pure JavaScript arrays. In the above code, ...theArgs is the rest parameter of the function add because it is the only named parameter, and it is also prefixed with ... (three dots). Since the rest parameter is a JavaScript array, you can perform operations such as push, pop, etc. on rest parameter theArgs, as shown in the code below:

function add(...theArgs){

    theArgs.push(10);
    var result = 0; 
    for(let i=0;i<theArgs.length;i++){
        result = result + theArgs[i];
    }
    var lastItem  = theArgs.pop();
    console.log(lastItem);
    return result; 
}

JavaScript functions' rest parameters can work with other parameters also. You may need other named parameters in your function if you do not want to include particular parameters in a rest parameter array. Let us consider next code block:

function add(num1, num2, ...theArgs){

    console.log(num1);
    console.log(num2);
    console.log(theArgs.length);

}
var r = add(6,9,3,2);
var t = add(7,56,9);

For a first-time function call, 6 and 9 will be assigned to num1 and num2 respectively. For the second function call, 7 and 56 will be assigned to num1 and num2. Parameters starting the third parameter will be assigned to the rest parameter array. Keep in mind that the first two parameters will not become part of the rest parameter array. So, if not all values should be included in the parameter, you should define those as a comma-separated named parameter in the beginning. The code given below will give you an error:

function add(num1, ...theArgs,num2){

    console.log(num1);
    console.log(num2);
    console.log(theArgs.length);

}

In the above code listing, the rest parameter is not the last parameter, so JavaScript will throw an error. The rest parameter must be the last formal parameter.

JavaScript allows you to destruct rest parameters, which means that you can unpack rest variable data into a distinct variable name. Let us consider the below code:

function add(...[a,b,c]){

    return a+b+c; 

}
var r = add(6);
console.log(r);
var t = add(7,56,9);
console.log(t);

For a first-time function call, a=6 , b= undefined, c = undefined will be assigned, and for the second function call, a=7, b=56, c=9 will be assigned. In this case, if you pass any extra parameter then that will be ignored in the function.

JavaScript function's rest parameter is a great improvement over the arguments object to work with unknown parameters of the function. It is a pure JavaScript array; hence, you can use all array methods with it. You can unpack the rest variable data to named variables. You can give any name to the rest parameters, which is again a major improvement over always using the arguments keyword.

In the next post of this "Easy JavaScript" series, you will learn about default parameters in JavaScript functions. You can learn in detail about these topics at the ECMA International site. Also, do not forget to check out Ignite UI, which you can use with HTML5, Angular, React, or ASP.NET MVC to create rich Internet applications.

Node.js application metrics sent directly to any statsd-compliant system. Get N|Solid

Topics:
web dev ,javascript ,rest parameter ,learning and development

Published at DZone with permission of Dhananjay Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}