Last updated on

In this post we’ll look at the JavaScript copy array task which is something a Junior Developer will come up against.

If you just need the code, here’s two solutions but read on to find out why you need to use one of these JavaScript copy array techniques and the difference between the two.

JavaScript Copy Array

const array1 = [1,2,3,4,5];

const copyOfArray1 = array1.slice();

// or …

const anotherCopyOfArray1 = [ …array1 ];

So if you’re wondering why you need to use the slice function (without any arguments you might notice) or the ES6 spread operator it’s because a JavaScript array is copied by reference.

Let’s take a look at what that means.

A JavaScript Array Copied By Reference

You might be forgiven for thinking to copy an array in JavaScript all you need to do is to create a new variable and assign it the same variable name as the original array.  For example:

const array1 = [1,2,3,4,5];

const copyOfArray1 = array1;

console.log(copyOfArray1); // 1,2,3,4,5

But watch what happens when you change the original array, like adding a new element:

array1.push(6);

console.log(array1); // 1,2,3,4,5,6

console.log(copyofArray1); // 1,2,3,4,5,6

Whoops! Looks like any changes we make to the original array are also made to the copy.  This because we’re not actually copying the array as such, we’re just copying a reference to the array not the values contained within the array itself.  

This is why we say it is an example of a JavaScript array copied by reference.

Using either the slice function on the array or the spread operator to create a new array allows us to make a copy of the array rather than just the reference of the array.

But which technique should you use?

Using slice() or the spread operator to copy a JavaScript array

So it’s a simple choice between using the slice function or the spread operator to copy a JavaScript array.  They both achieve the same effect.

I would say to prefer using the spread operator as it’s more succinct and more obvious what you are trying to do.  The slice function should really only be used now if you’re trying to support older browsers (Internet Explorer anyone?) that may not have support for the spread operator.

Conclusion

That’s it! Just use the spread operator where possible to copy an array in JavaScript.

You might want to check out some of the other articles in my JavaScript Snippets series: …