What is the spread operator in JavaScript and how to use it

What is the spread operator in JavaScript and how to use it

while copying or cloning an array

What is the spread operator anyway?

In JavaScript the syntax of the spread operator is three consecutive dots (...) and it is used to expand an iterable object in list of arguments.

The spread operator was added to JavaScript in ES6.

The (…) spread operator is useful for many different tasks in JavaScript, including the following:

  • Copying an array
  • Concatenating or combining arrays
  • Using an array as arguments
  • Adding an item to a list
  • Adding to state in React
  • Combining and copying of objects

In this blog we will see how to use the (...) with arrays while cloning one

Cloning an array ( the Wrong and the Right way)

The Wrong Way

Let's take an array and make a copy of it by just assigning it to other variable by only using assignment operator(=)

let arr = [1, 2 ,3, 4, 5]
let clone = arr

So far so good but now let's try changing the elements for the clone array

clone[2]=9
console.log("original array" ,arr)
console.log("clone array" , clone)

the output we get is-

original array [ 1, 2, 9, 4, 5 ]
clone array [ 1, 2, 9, 4, 5 ]

Not something we were expecting right? both the arrays are manipulated but we only wanted that to happen with the clone array, basically changing the clone array is also mutating the original array.

So , this was the wrong way of making a copy of the array when you do not want to mutate your original array.

Let's see why it has happened-

When we create a copy of an array using (=), we've only copied the address. We have NOT copied the array, which is what we want. To do this we need to assign the array with a new address or reference. That way, when we make changes to our new array, it won't affect the original array because they will be at different addresses.

The Right Way

(Here the spread operator comes into play)

consider we write the same code that we wrote above as -

let arr = [1,2 ,3 ,4, 5]
let clone = [...arr] // The spread operator

clone[2]=9
console.log("original array", arr)
console.log("clone array",clone)

so now what spread operator will do is it will provide the clone array a new address and will also get the elements inside the original array to it. So in that way we have two copies of the same array but in different addresses.

So now the we will get the output as-

original array [ 1, 2, 3, 4, 5 ]
clone array [ 1, 2, 9, 4, 5 ]

This is the right way of cloning an array so that manipulating the clone array does not effect the original array.