Spread Operator in ES6

Spread operator is similar to rest parameter in JavaScript 6. If rest parameter groups a set of arguments to one array, Spread operator distributes an array elements to separate arguments.

I have a function which accepts 3 parameters.

1
2
3
4
5
functionmyFun(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
}

Spread operator uses a … syntax. See below how I call above function. Both techniques do the same thing.

1
2
myFun(2, 4, 6);
myFun(...[2, 4, 6]);

The spread operator tears the array and supply each element to a, band c. Scope of rest parameters constrain to function arguments. Where as spread operator comes handy in several situations.

Inserting array inside array using spread operator

See how we can insert one array inside another using spread operator.

1
2
3
var arr1 = [2, 4, 6];
var arr2 = [1, 3, ...arr1, 5, 7];
console.log(arr2); // [1, 3, 2, 4, 6, 5, 7]

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *