In JavaScript, there are 5 simple ways to copy an array to another array. Here are some examples and explanations.
1. Using the Spread Operator (...)
The newest and easiest way (ES6 and above):
const original = [1, 2, 3];
const copy = [...original];
console.log(copy); // [1, 2, 3]
2. Using slice()
A traditional method for making a shallow copy:
const original = ['a', 'b', 'c'];
const copy = original.slice();
console.log(copy); // ['a', 'b', 'c']
3. Using Array.from()
Turns an iterator (like an array) into a new array:
const original = [10, 20, 30];
const copy = Array.from(original);
console.log(copy); // [10, 20, 30]
4. Using concat()
Copies the original array by adding an empty array:
const original = [true, false, true];
const copy = original.concat();
console.log(copy); // [true, false, true]
5. Using map()
Iterates through and returns every item (rare but feasible):
const original = [{ name: 'Alice' }, { name: 'Bob' }];
const copy = original.map(item => item);
console.log(copy); // [{ name: 'Alice' }, { name: 'Bob' }]
Shallow Copy vs. Deep Copy
Shallow Copy
The methods above copy primitive values (numbers, strings), but reference objects (arrays/objects inside an array) still refer to the same memory location as the original.
const original = [{ x: 1 }];
const copy = [...original];
copy[0].x = 99;
console.log(original[0].x); // 99 😱
Deep Copy
For nested arrays/objects, use:
const deepCopy = JSON.parse(JSON.stringify(original));
Note: This does not work for Date objects, functions, or circular references.
Which Method Should You Use?
Use Spread Operator ([...arr]) or Array.from() → Suitable for most cases.
Need browser support for older code? → Use slice()
Need a deep copy? → Use JSON.parse(JSON.stringify(arr)) (with restrictions) or a library like _.cloneDeep() from Lodash.
Common Mistake
🚨 Do not assign arrays directly! This only creates a reference, not a copy.
const original = [1, 2, 3];
const badCopy = original; // Both point to the same array!
badCopy.push(4);
console.log(original); // [1, 2, 3, 4] 😱
Let me know if you need any further improvements! 😊
No comments