What is rest operator in javascript?

Rest operator javascript: we indicate for the rest parameter from three dots(…). We use it as a parameter if we required in future can come more parameter then using with three dots. Always we use as a last parameter. Rest operator and spread operator both using three dots. As below example:

// this is simple function

    function restOperator (arg){

        return arg+1;

    }

    console.log(restOperator); 

    /* ƒ restOperator (arg){

        return arg+1;

    }*/

 

    console.log(restOperator()); // NaN

    console.log(restOperator(5)); // 6

 

    // this is arrow function

    const restOperatorNew = (arg) => arg

    console.log(restOperatorNew(5)); // 6

    console.log(restOperatorNew(10)); // 11

 

    // need to use rest operator

    const restOpSingle = (...arg) => arg

    console.log(restOpSingle(2)); // [2]

 

    const restOp = (...arg) => arg

    console.log(restOp(2,4)); // [2, 4]

 

    const arrss = [1,2,3];

    const restOpNumber = (...arg) => arg ;

    console.log(restOpNumber(arrss)); //[Array(3)]

 

    const restOpLast = (arg) => arg

    console.log(restOpLast('sheo''sagar')); // sheo

 

    const restOpLast1 = (...arg) => arg

    console.log(restOpLast1('sheo')); // ["sheo"]

 

    const restOpLastRest = (...arg) => arg

    console.log(restOpLastRest('sheo''sagar')); // ["sheo", "sagar"]

 

    /*const restOpWithArg = (...arg, ss) => arg

    console.log(restOpWithArg('sheo', 'sagar')); 

    // Uncaught SyntaxError: Rest parameter must be last formal parameter*/

 

    const restOpWithArgLast = (ss, ...arg) => ss + arg

    console.log(restOpWithArgLast('sheo ''sagar')); // sheo sagar

    

    /*const restOpWithArgLast1 = (...arg) => ss + arg

    console.log(restOpWithArgLast1('sheo ', 'sagar', 'contact', 1 , 5)); 

    // Uncaught ReferenceError: ss is not defined*/

 

    const restOpWithArgLast2 = (ss,...arg) => ss + arg

    console.log(restOpWithArgLast2('sheo ''sagar''contact'1 , 5)); 

    // sheo sagar,contact,1,5


 

No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.