JavaScript ES2018: Understanding the Spread and Rest Operator

The introduction of ES2018
has been a delight to several javascript developers as it unlocks several features that make it easier to do complex computations, ...
is one of these new Javascript functionalities. It can be used in two different ways; as a spread operator
OR as a rest parameter
. This article focuses on these two operators.
Spread
syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
--MDN documentation
The rest
parameter syntax allows us to represent an indefinite number of arguments as an array.
--MDN documentation
Spread Operator
Spread
Operator is introduced in javascript in ES6
. This operator makes copying and merging arrays much easier. Rather than calling the concat()
or slice()
method, you could use the ...
operator:
const arr1 = ['A', 'B', 'C'];
const copy = [...arr1]; // make a copy of arr1
console.log(copy); // → ['A', 'B', 'C'];
const arr2 = ['D', 'E'];
const merge = [...arr1, ...arr2]; // merge arr2 with arr1
// so now merge will look like → ['A', 'B', 'C','D','E']
console.log(merge);
ES2018
further expands this syntax by adding spread properties to object
literals. With the spread properties you can copy own enumerable properties of an object onto a new object. Consider the following example:
const obj1 = {
a: 1,
b: 2
};
const obj2 = {
...obj1,
c: 3,
d: 4
};
console.log(obj2); // → {a: 1, b: 2, c: 3, d: 4}
Rest Operator
From the definition we saw earlier, rest parameters
collect all the remaining elements into an array. This allows us to do really neat function definitions. Let's see how we put them to use.
const arr1 = ['A', 'B', 'C'];
const [i, ...rest] = arr1;
console.log(i); // → A
console.log(rest); // → ['B', 'C']
This feature is really very helpful and became so popular that the Ecma Committee decided to bring a similar functionality to objects. Let's see how we put them to use.
const obj1 = {
a: 1,
b: 2,
c: 3
};
const {i, ...rest} = obj1;
console.log(i); // → 1
console.log(rest); // → {b: 2, c: 3}
Note: Rest parameters have to be at the last argument
. This is because it collects all remaining/ excess
arguments into an array.
Conclusion
So, if you want to copy values of iterables
(Objects/Strings/Arrays), make use of spread
and If you want specific items to be excluded from the copy, make use of destructuring and the rest operator
.
I hope this article makes these two concepts clearer. For a very simplified explanation on the difference, I personally loved this illustration by Faraz Kelhini. Make sure to follow him on twitter for similar code facts illustrations.
Like this article? Follow @hemantjava Twitter