Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Rest Parameters in JavaScript

Rest Parameters in JavaScript allow us to accept a variable number of arguments as an array. JavaScript introduced this feature in ES6. It is now the preferred way to access the variable number of arguments. Before Rest Parameters, the only way to do this was to use the Arguments object.

Rest Parameters

We generally use the parameters to access the arguments inside the function. But JavaScript allows us to pass any number of arguments to a function irrespective of the number of parameters it declares.

The following addNum function declares two parameters. But we can invoke it with three or more arguments. JavaScript does not complain. But we cannot access those additional arguments using the existing parameters.

                            
function addNum(a, b) {
    return a + b ;
}
 
//0 Argument.   Both a & b is initialzed as undefined
console.log(addNum());              //Nan
 
//1 Argument    b is initialzed as undefined
console.log(addNum(1));             //Nan
 
//2 Argumnets
console.log(addNum(1,2));           //3
 
//3 Arguments   last argument 3 is ignored
console.log(addNum(1,2,3));         //3
 
 
                            
                        
                            
                        

There are two ways using which we can access those additional arguments. One is to use the arguments object and the other is to use the Rest Parameters.

Using Rest Parameter

Rest Parameters in JavaScript lets us store the extra arguments that we supply to the function into an array.

Syntax

The syntax of the Rest Parameters is shown below. We prefix the rest Parameter with ... (three dots) followed by the name of the rest parameter.

                            
function f(a, b, ...args) {
  // …
}
 
 
 
                            
                        
                            
                        

In the above syntax args is the rest parameter, while a & b are normal parameters.

JavaScript assigns the arguments to parameters starting from left to right. First, it assigns the values to the regular parameters a & b. When it encounters a rest parameter it creates an array of all remaining arguments and assigns it to the Rest Parameter i.e. args.

In the following example, fnRest declares args as the rest parameter along with regular parameters a & b. As you can see the first two arguments (1 & 2 ) are mapped in the parameters a & b. The remaining arguments are stored as an array in the rest Parameter args.

                            
function fnRest(a, b, ...args) {
  
  console.log("a", a);
  console.log("b", b);
  console.log("args", args);
}
 
fnRest(1,2,3,4,5);
 
//Output:
 
//a 1
//b 2
//args [ 3, 4, 5 ]             //All addtional arguments are now stored in array
 
 
                            
                        
                            
                        

Even if there is just one extra argument, it will be saved as a single element of an array.

                            
function fnRest(a, b, ...args) {
  
  console.log("a", a);
  console.log("b", b);
  console.log("args", args);
}
 
fnRest(1,2,3);
 
//Output:
 
//a 1
//b 2
//args [ 3 ]               //Array with single element
 
 
                            
                        
                            
                        

If there is no argument provided for the rest parameter, we get an empty array

                            
function fnRest(a, b, ...args) {
  
  console.log("a", a);
  console.log("b", b);
  console.log("args", args);
}
 
fnRest(1);
 
//Output:
 
//a 1
//b undefined
//args []                        //Empty Array
 
 
                            
                        
                            
                        

The Rest Parameters must appear last in the Parameter list.

                            
function f(a,  ...restPara, b)   //Wrong
function f(...restPara,a, b)     //Wrong
 
 
 
                            
                        
                            
                        

There can be only one rest parameter in a function.

                            
function f(a, b, ...restPara1, ...restPara2)    //Wrong 
 
 
 
                            
                        
                            
                        

Rest Parameters Example

The following example nums is a rest parameter. We invoke AddNum many arguments. All of them are captured in the nums array. We then loop through it using for loop and calculate the sum

                             
function AddNum(...nums){
    let sum = 0;
    for(let i of nums){
        sum+=i;
    }
    return sum;
}
 
console.log(AddNum(1,2));                          // 3
console.log(AddNum(1,2,3));                       // 6
console.log(AddNum(1,2,3,4,5));                 // 15    
console.log(AddNum(1,2,3,4,5,6,7,8,9,10));  // 55  
 
 
                            
                        
                            
                        

Rest Parameter Vs Argument Object

The Argument object is another way to access the arguments in JavaScript. It is available inside every JavaScript function. It contains the values of the arguments passed to that function in an array-like structure. There are some differences between Rest Parameters Vs Arguments Object

The argument object contains all of the arguments. Whereas the rest parameters contain only the extra arguments. It will not contain the parameter which appears before the declaration of the Rest Parameter.

The arguments object is always available in every function (except the Arrow function). We need not do anything to declare them. The Rest Parameters must be explicitly declared.

The arguments object is not available in Arrow functions. We can use Rest Parameters in Arrow functions.

The arguments object has a callee property that returns the reference to the executing function to which the arguments belong. This property is not available in a strict mode. The Rest Parameter does not have that property.

In a non-strict mode, any changes made to the arguments object will also change the parameter ad vice versa. This is not an issue in the rest parameters.