How to Copy Array by Value in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the slice()
Method
You can simply use the slice()
method to create a copy of a JavaScript array that behaves independently. This method returns a shallow copy of a portion of an array into a new array.
Let's try out the following example to understand how it basically works:
Example
Try this code »// Original array
var array1 = ["red", "green", "blue"];
// Making a copy
var array2 = array1.slice();
// Adding a new element to copied array
array2.push("pink");
console.log(array2); // Prints: ['red', 'green', 'blue', 'pink']
console.log(array1); // Prints: ['red', 'green', 'blue']
Alternatively, in ES6 you can easily make an independent copy of an array by using the spread operator (...
). Let's take a look at an example to understand how it actually works:
Example
Try this code »// Original array
var array1 = ["red", "green", "blue"];
// Copying the array
var array2 = [...array1];
// Adding a new element to copied array
array2.push("pink");
console.log(array2); // Prints: ['red', 'green', 'blue', 'pink']
console.log(array1); // Prints: ['red', 'green', 'blue']
Related FAQ
Here are some more FAQ related to this topic: