Learning ES6 (LR)-02

How ECMAScript 6 (ES6) Rest Operators ( … ) Work?

The ECMAScript 6 offers a crucial feature to developers in the form of Rest operators. These operators standardize JavaScript and operate on specific fields in an array. The array is split into two distinct portions—one that denotes distinct objects and the other storing all the remaining fields into the newly-created restful object. The Rest operators can also be destructed which means that they can be unpacked into distinct function parameters and can perform array and hash manipulation. The number of parameters that the operator can take varies from 0 (inclusive) to theArgs.Length (exclusive).

Case 1: Dealing with Arrays

Suppose if you want only two fields (a, b) from the Array then in such a scenario, fields 1 and 2 are retained in the array, while rest of the fields (see example below) 3, 4, and 5, are stored in a single ‘rest’ parameter.

Rest Operators

`a` , `b` , `…rest` divides the array into three distinct parameters ( also known as Destruction ).

Case 2: Dealing with Objects

Now let us extract data from objects. The below example retains the first two fields ‘a’ and ‘b’ in the original array. The rest of the fields, c, d, and e, are stored in the ‘rest’ parameter along with their values 30, 40, and 50 respectively.

Rest Operators 1

Here the two concepts are working together—Destruction and the Rest Operator.  

The ‘rest’ parameter will store all the other objects/sub-objects that succeed ‘a’ and ‘b.’

Rest Operators 3


Case 3: Dealing with Complex Objects

If you want to change the value of `a` in the object then you can do it in the following manner. 
 

Rest Operators 4

We can also assign a new object with the same value as an existing object then in that case both the objects (OLD and NEW) will be changed because objects are saved by REFERENCES.

Rest Operators 5

We can take help of the ‘rest’ operator to fix the above issue.

Rest Operators 6

What will this do? Any idea?

It will include the entire object inside the NEW object (as named newObject ) and then modify the field `a` if it is present or add the new key to the object. 


What if I change the order?

Rest Operators 7

Nothing will happen here because first, we are adding a key `a` in the new object then we are modifying that with the old object. So this will give the same result as the old object.

I know what you are saying?

Rest Operators 8

The ‘Rest ‘will Rule

It can be clearly seen that the ‘…rest’ operator segregates an array of fields using its ‘destruction’ behavior. This phenomenon helps the programmer in dealing with complex objects and assigning specific values to data objects dynamically during the execution of the code.