The spread operator basically expands an array into all its elements, unpacking all the array elements at one.
You can see an example in the above code, we expand an array. so new Array, we get the exact same result with badnews array. Spread operate does is to basically take all the values out of this arr and then write them individually as if we wrote seven, eight, nine manually.
Spread operator using
three
dots (…)
We can use spread operator whenever we would otherwise write multiple values separated by commas.
Second things that we can do with spread operator is we can pass arguments into functions.
What else can …
do?
The …
spread operator is useful for many different routine tasks in JavaScript, including the following:
- Copying an array
- Concatenating or combining arrays
- Using Math functions
- Using an array as arguments
- Adding an item to a list
- Adding to state in React
- Combining objects
- Converting NodeList to an array
In each case, the spread syntax expands an iterable object, usually an array, though it can be used on any iterable, including a string.
One of the benefits of using the spread operator is that it will create a new reference to its primitive values, copying them.
That means that changes to the original array will not affect the copied array, which is what would happen if the array had been linked to the original with the assignment operator =
:
The spread operator …
is useful for working with arrays and objects in JavaScript. It is a convenient feature added in ES6 (ES2015).
I also like that it can quickly combine the properties of objects into a new object, though any properties whose names conflict will be lost.
Knowing the spread syntax definitely saves me time when coding, and I recommend using it to all JavaScript developers.