Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Create new array without impacting values from old array in JavaScript?
In JavaScript, directly assigning an array to a new variable creates a reference to the original array, not a copy. This means changes to the new variable will affect the original array. To create a truly independent copy, you need to use specific cloning methods.
The Problem with Direct Assignment
When you assign an array directly, both variables point to the same array in memory:
var originalArray = ["John", "Mike", "Sam", "Carol"];
var newArray = originalArray; // This creates a reference, not a copy
newArray.push("David");
console.log("Original array:", originalArray);
console.log("New array:", newArray);
Original array: [ 'John', 'Mike', 'Sam', 'Carol', 'David' ] New array: [ 'John', 'Mike', 'Sam', 'Carol', 'David' ]
Using slice() Method (Recommended for Simple Arrays)
The slice() method creates a shallow copy of the array:
var listOfNames = ["John", "Mike", "Sam", "Carol"];
var namesArray = listOfNames.slice();
namesArray.push("David");
console.log("Original array:", listOfNames);
console.log("New array:", namesArray);
Original array: [ 'John', 'Mike', 'Sam', 'Carol' ] New array: [ 'John', 'Mike', 'Sam', 'Carol', 'David' ]
Using Spread Operator (ES6)
The spread operator provides a clean, modern syntax for array cloning:
var listOfNames = ["John", "Mike", "Sam", "Carol"];
var namesArray = [...listOfNames];
namesArray[0] = "Johnny";
console.log("Original array:", listOfNames);
console.log("New array:", namesArray);
Original array: [ 'John', 'Mike', 'Sam', 'Carol' ] New array: [ 'Johnny', 'Mike', 'Sam', 'Carol' ]
Using JSON.parse(JSON.stringify()) for Deep Copy
For arrays containing objects or nested arrays, use JSON methods for deep cloning:
function createNewArray(listOfNames) {
return JSON.parse(JSON.stringify(listOfNames));
}
var complexArray = [
{name: "John", age: 25},
{name: "Mike", age: 30}
];
var deepCopy = createNewArray(complexArray);
deepCopy[0].name = "Johnny";
console.log("Original:", complexArray);
console.log("Deep copy:", deepCopy);
Original: [ { name: 'John', age: 25 }, { name: 'Mike', age: 30 } ]
Deep copy: [ { name: 'Johnny', age: 25 }, { name: 'Mike', age: 30 } ]
Comparison
| Method | Speed | Nested Objects | Browser Support |
|---|---|---|---|
slice() |
Fast | Shallow copy only | All browsers |
[...array] |
Fast | Shallow copy only | ES6+ |
JSON.parse(JSON.stringify()) |
Slower | Deep copy | All browsers |
Conclusion
Use slice() or spread operator for simple arrays, and JSON.parse(JSON.stringify()) for deep copying nested objects. Always create copies to avoid unintended mutations of the original array.
