Rest Parameters (...)

JavaScript Rest Parameters ..., i.e three full stops are used in functions using resp operator (...). It is used as last parameter of function only. The rest operator prefix replace all parameters to JS Arrays. By using rest parameter, we can add n numbers of arguments without defining parameters.

The Rest Parameter is different from spread operator, although they look same. The Rest Operator (...) extracts Arrays and is used for Rest Parameters and Destructuring.

Resp Parameters Example

[1,2,3]


    function toArray(...args){
        return args;
    }
    console.log( toArray(1,2,3) );

Rest Operator (...)

Rest parameters are used using rest operator (...). The triple dot or full stop is actually resp operator. Its is used as prefix to functions last parameter.

Earlier we use arguments keyword, but

Check Parameters count using resp operator

3


    function checkLength(...x){ 
        let count=0;
        for( let i in x){
            count=count+1; 
        } 
        return count;
    };
    console.log(7,8,9);

Check Arguments length

How to check number of arguments in javascript using rest operator.

4


    function checkLength(...x){ 
        return x.length;
    };
    console.log( checkLength(3,4,5,6) );

arguments object

To check number of arguments in javascript in ES5, use arguments object. arguments object is not available in arrow functions.

3


    function checkLength(){ 
        return arguments.length;
    };
    console.log( checkLength(6,7,8) );