-- Main.shssdhakchina - 26 Jan 2022

The Spread Operator

Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows us the privilege to obtain a list of parameters from an array. Syntax of Spread operator is same as Rest parameter but it works completely opposite of it.

Syntax:

var variablename1 = [...value];
In the above syntax, … is spread operator which will target all values in particular variable. When … occurs in function call or alike,its called a spread operator.

// spread operator doing the concat job
let arr = [1,2,3];
let arr2 = [4,5];
  
arr = [...arr,...arr2];
console.log(arr); // [ 1, 2, 3, 4, 5 ]

Rest Parameter

Rest parameter is an improved way to handle function parameter, allowing us to more easily handle various input as parameters in a function. The rest parameter syntax allows us to represent an indefinite number of arguments as an array. With the help of a rest parameter a function can be called with any number of arguments, no matter how it was defined. Rest parameter is added in ES2015 or ES6 which improved the ability to handle parameter.

Syntax:

function functionname(...parameters)   //... is the rest parameter (triple dots)
{
statement;
}
Note: When … is at the end of function parameter, it is the rest parameter. It stores n number of parameters as an array. Let’s see how the rest parameter works:

// es6 rest parameter
function fun(...input){
    let sum = 0;
    for(let i of input){
        sum+=i;
    }
    return sum;
}
console.log(fun(1,2)); //3
console.log(fun(1,2,3)); //6
console.log(fun(1,2,3,4,5)); //15

This topic: ReactJs > WebHome > ExploringECMAScript6(ES-6) > TheSpreadRestOperators
Topic revision: 26 Jan 2022, shss\dhakchina
This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Foswiki? Send feedback