Using Spread operator in Javascript

Tram Ho

Hi everyone,
In this article, I will share how to use the **spread** operator.
The spread operator is defined with 3 dots (…). Eg:
Javascript const odd = [1,3,5]; const combined = [2,4,6, ...odd]; console.log(combined); Output:
Javascript [ 2, 4, 6, 1, 3, 5 ] In the above example the 3 dots (…) in front of the odd array is the spread operator. It is responsible for unpacking the elements in the odd array.
In ES6 also use ellipsis (…) to define a **rest parameter** . It has the job of gathering all the remaining parameters in the function into an array.
Javascript function f(a, b, ...args) { console.log(args); } f(1, 2, 3, 4, 5); Output:
Javascript [ 3, 4, 5 ] Difference between spread and rest parameter.
* The spread operator unpacks the elements in an array * Rest parameter collects the remaining elements of the function into an array When using the rest parameter, it must be the last parameter of the array, otherwise it cannot be used . However, the spread operator can be placed anywhere. for example:
Javascript const odd = [1,3,5]; const combined = [...odd, 2,4,6]; console.log(combined); Output:
Javascript [ 1, 3, 5, 2, 4, 6 ] Or
Javascript const odd = [1,3,5]; const combined = [2,...odd, 4,6]; console.log(combined); Output:
[ 2, 1, 3, 5, 4, 6 ]

Share the news now

Source : Viblo