Spread operator: Code Pen
The spread operator helps to extract the collected elements into a single element and used to merge two elements.
Spread Syntax […spread]
Spread Operator extracts the collected elements to a single element. In the example below, see the output is extracted as individual elements 1, 2, 3, 4.
Why Spread Operator?
In JavaScript variables are immutable, but objects and array are mutable. The spread operator helps to achieve these objects & arrays to be immutable.
In the example below,
Modify the var copy => make a copy of x in y and then modified the reference y, the original value x is still remains the same. (immutable)
Modify the Object copy =>For Object & Array, make a copy of x in y and then modified the reference y, the original value x is also updated. (mutable)
How to resolve this?
The spread operator helps to update the copy without modifying the original Object.
In the example below, the profile object is the reference or copy which merges the userDetails and acctDetails object and then updated the acctType to produce a new object. Still, the original values of userDetails and acctDetails remain the same.
The task to the reader: Apply the same concept using Array
String with space […spread]
It extracts the given string into a single element and allows the storage of an Object or Array. Space is also considered an element.
[…spread] as an argument
In the example below, the arrSum method call having the argument as a spread operator.
Rest Operator [rest…]
The rest operator is known for de-structuring of elements, then it collected the leftover elements to make it an array or object, which is exactly opposite to the spread operator.
Applies to Array [rest…]
In the example below, de-structuring of elements happened for the first two elements and the leftover elements are collected into a new sub-array.
The task to the reader: Apply the same concept using Object, also the example is available in the Code Pen
Hope it will give a clear view of Spread and Rest Operators, Please write your questions for any doubts or corrections.
Let’s discuss the next feature of ES6 in the next story.
Next topic: Template Literals