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.
`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.
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.’
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.
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.
We can take help of the ‘rest’ operator to fix the above issue.
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?
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?
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.