In JavaScript, copying an array is not as simple as using the assignment operator (=) to create a duplicate. If you’ve ever tried this, you will be surprised to find out that it only creates a link to the original list. What’s the deal?
In this guide, we’re going to talk about how to copy a JavaScript array. We’ll walk through the code for three JavaScript copy array strategies so you can get started copying arrays.
The Problem with Copying JavaScript Arrays
On some level, the “=” operator creates a copy of an array into a new variable. It’s more of a pointer than a copy though. This is because the “=” operator creates a reference to an original array. It does not create a duplicate of the existing array.
Let’s try to create a copy of an array using the assignment operator with no other code:
var berries = ["Strawberry", "Gooseberry", "Raspberry"]; var fruits = berries; console.log(fruits);
Our code returns:
[ "Strawberry", "Gooseberry", "Raspberry" ]
It looks like our array has been copied. “fruits” contains all the values from our “berries” array.
Now, let’s try to add an item to the “fruits” array:
fruits.push("Melon"); console.log(fruits); console.log(berries);
We have added “Melon” to the fruits array. We then print out the values of “fruits” and “berries” to the console:
[ "Strawberry", "Gooseberry", "Raspberry", "Melon" ] [ "Strawberry", "Gooseberry", "Raspberry", "Melon" ]
Both “fruits” and “berries” contain the same values. That’s because we have not technically cloned our array. We’ve just created a reference to it.
Any time we manipulate the “berries” array, the changes will be made in the “fruits” array.
How to Copy a JavaScript Array
The assignment operator does not copy an array. We’ve got to use another approach. Luckily for us, there are plenty of ways to create a copy of an array. The top three approaches are:
- Using the spread operator
- Using a for loop
- Using Array.from
Let’s discuss these one-by-one.
Using the Spread Operator
The spread operator is a feature introduced in JavaScript ES6. It allows you to access the contents of an iterable object. This operator is often used to create a shallow copy of an array.
The spread operator consists of three dots, like an ellipsis (…). Let’s try to create a copy of our “berries” array from earlier:
var berries = ["Strawberry", "Gooseberry", "Raspberry"]; var fruits = [...berries]; fruits.push("Melon");
We’ve used the spread operator to create a copy of our array. Let’s check the values of our arrays to make sure they are correct:
console.log(berries); console.log(fruits);
Our code returns:
[ "Strawberry", "Gooseberry", "Raspberry" ] [ "Strawberry", "Gooseberry", "Raspberry", "Melon" ]
The value “Melon” was only added to the “fruits” array. This is because we used the spread operator to create a duplicate of the “berries” array. Now, the “fruits” array is its own array. Its values are separate from the “berries” array.
Using a for Loop
The tried and true method, using a for loop is a good way to create a copy of an array.
This method may not be as favored as the spread operator because it requires more lines of code. With that said, a for loop copies an object well.
var berries = ["Strawberry", "Gooseberry", "Raspberry"]; var fruits = []; for (var i = 0; i < berries.length; i++) { fruits[i] = berries[i] }
We’ve declared two lists: berries and fruits. Fruits is initially an empty list. Then, we’ve used a for loop to loop through every item in the “berries” list. For each item in the list, the value is copied over to the “fruits” array.
Let’s run our test to see if our arrays are separate:
fruits.push("Grapefruit"); console.log(berries); console.log(fruits);
Our code returns:
[ "Strawberry", "Gooseberry", "Raspberry" ] [ "Strawberry", "Gooseberry", "Raspberry", "Grapefruit" ]
Success! “berries” and “fruits” are two separate arrays.
Using Array.from()
The Array.from()
method turns any iterable object into an array. It goes through each item in an iterable and appends it to a new array. This means that it can be used to copy an array.
Let’s create a copy of our “berries” array again:
var berries = ["Strawberry", "Gooseberry", "Raspberry"]; var fruits = Array.from(berries);
This solution, like the spread operator syntax, only takes up two lines of code. It’s an efficient and concise way of copying an array. Now, let’s run a test to check our new arrays:
fruits.push("Pineapple"); console.log(berries); console.log(fruits);
Our code returns:
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
[ "Strawberry", "Gooseberry", "Raspberry" ] [ "Strawberry", "Gooseberry", "Raspberry", "Pineapple" ]
Our arrays have been successfully copied.
Conclusion
Copying an array in JavaScript is easy when you know how.
The assignment operator isn’t enough to copy an array if you want to create a separate version of an array. This is because the assignment operator creates a pointer to an existing array; it does not create a new array.
You can create a copy of an array using the spread operator, a for loop, or the Array.from()
method. Now you’re ready to copy arrays in JavaScript like an expert.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.