ES6 has introduced many new features into JavaScript, among them the spread operator (...), which expands an iterable object into a list of its individual elements.

If it’s not clear yet, don’t worry, we will go into details in the next sections when we actually learn to use it with real-life scenarios.

Copy arrays or objects

Look at the following script, can you tell what’s the output?

const listA = [1, 2, 3]
const listB = listA
listB.push(4)
console.log('listA:', listA)
console.log('listB:', listB)

The output for that example is the following:

"listA:" [1, 2, 3, 4]
"listB:" [1, 2, 3, 4]

Wait! what? Why did listA changed its value when we clearly only changed listB. Well, the reason is simple, when we did the assignment:

const listB = listA

Javascript assigned to listB a reference to listA, so in essence listA and listB are pointing to the same list in memory.

So then, how do I create a copy? Here is where spread operators enter the picture. Let’s look again at the same example using spread operators:

const listC = [1, 2, 3]
const listD = [...listC]
listD.push(4)
console.log('listC:', listC)
console.log('listD:', listD)

And the output:

"listC:" [1, 2, 3]
"listD:" [1, 2, 3, 4]

In this case, by using the spread operator we are making a new copy in memory of the array, so when we update listD we are not affecting by any means listC.

#javascript #programming #spread operator

How to Use the Spread Operator (...) in JavaScript
1.35 GEEK