Spread And Rest Operator

In Javascript, both the spread and rest operators have the same syntax which is three dots(…) but they differ in their function. The main difference between them is that the spread operator expands the array into multiple elements while the resting operator

Condenses them into a single element

Merge two arrays using the spread operator

A Spread operator can be used to merge multiple arrays containing one or more elements into a single array.

 

Copy array using the spread operator

The Spread operator is also used to create a copy of an array. In the following example when an element is pushed to “arr2” it also updates the original array “arr1”.To avoid this Spread operator is used to create a copy array to avoid updating the original array.

 

Rest operator with function

The Spread operator allows the function to accept multiple arguments as an array. It is also used with destructuring to combine remaining elements into a single element.

 

Rest operator with destructuring

Rest operator can also be used with destructuring as the last element to combine the remaining element of the array into a single array. In the following example “location” will contain all the remaining elements of the array.

 

 

Leave a Reply