I am confused about the spread syntax and rest parameter in ES2015. Can anybody explain the difference between them with proper examples?
ES6 has new feature three dots ...
Here is how we can use these dots:
- As Rest/Collector/Gather
var [c, ...m] = [1,2,3,4,5]; // m -> [2,3,4,5]
Here ...m
is a collector, it collects the rest of the parameters. Internally when we write:
var [c, ...m] = [1,2,3,4,5];
JavaScript does following
var c = 1,
m = [2, 3, 4, 5];
- As Spread
var params = [ "hello", true, 7 ];
var other = [ 1, 2, ...params ]; // other => [1,2,"hello", true, 7]
Here, ...params
spreads so as to adding all of its elements to other
Internally JavaScript does following
var other = [1, 2].concat(params);
Hope this helps.
In javascript the ...
is overloaded. It performs a different operations based on where the operator is used:
Rest parameter syntax:
function rest(first, second, ...remainder) {
console.log(remainder);
}
// 3, 4 ,5 are the remaining parameters and will be
// merged together in to an array called remainder
rest(1, 2, 3, 4, 5);
Spread syntax:
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
// the numbers array will be spread over the
// x y z parameters in the sum function
console.log(sum(...numbers));
// the numbers array is spread out in the array literal
// before the elements 4 and 5 are added
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers);
When we see "..." in the code, it is either rest parameters or the spread operator.
There’s an easy way to distinguish between them:
When ... is at the end of function parameters, it’s “rest parameters” and gathers the rest of the list into the array. When ... occurs in a function call or alike, it’s called a “spread operator” and expands an array into the list. Use patterns:
Rest parameters are used to create functions that accept any number of arguments. The spread operator is used to pass an array to functions that normally require a list of many arguments. Together they help to travel between a list and an array of parameters with ease. For more information about this click here
Basically like in Python:
>>> def func(first, *others):
... return [first, *others]
>>> func('a', 'b', 'c')
['a', 'b', 'c']