There are several ways to copy an array in JavaScript:
[...arr] — most modern way 🆕arr.slice() — classic way 📚arr.concat() — another way 🔗Array.from(arr) — universal way 🌐const original = [1, 2, 3];
// Spread — most common way
const copy1 = [...original]; // [1, 2, 3]
// slice — classic way
const copy2 = original.slice(); // [1, 2, 3]
// Important: this is shallow copy!Copying an array is like taking a photo of a box with items. You get a new box with the same items, but it’s a separate box! 📦📸
Copies only the “surface” of the array. If there were objects in the array, references to them are copied, not the objects themselves:
const fruits = ['apple', 'banana', {name: 'orange'}];
// Copy array
const copy = [...fruits];
// Change in copy
copy[0] = 'pear';
console.log(fruits[0]); // 'apple' — original unchanged
console.log(copy[0]); // 'pear' — copy changed
// But objects are the same!
copy[2].name = 'tangerine';
console.log(fruits[2].name); // 'tangerine' — shared object!const arr = [1, 2, 3];
// Empty slice — copies entire array
const copy = arr.slice();
// Same as [...arr]const original = [1, 2, 3];
// concat without parameters
const copy1 = original.concat();
// Array.from
const copy2 = Array.from(original);
// All do the same — shallow copyCopies everything, including nested objects. Each object becomes new:
const arr = [1, {name: 'John'}, [2, 3]];
// Deep copy via JSON
const deepCopy = JSON.parse(JSON.stringify(arr));
// Now objects are different
deepCopy[1].name = 'Peter';
console.log(arr[1].name); // 'John' — original unchanged⚠️ Important: JSON method doesn’t work with functions, undefined, Symbol and other special values!
// ✅ For arrays with simple values
const numbers = [1, 2, 3];
const copy = [...numbers];// ✅ For arrays with objects, if full separation needed
const complex = [{user: 'John'}, {user: 'Peter'}];
const deep = JSON.parse(JSON.stringify(complex));// ❌ Mistake — this is not a copy, but a reference!
const arr1 = [1, 2, 3];
const arr2 = arr1; // Not copy, but reference to same array!
arr2[0] = 999;
console.log(arr1[0]); // 999 — original changed!
// ✅ Correct — make real copy
const arr3 = [...arr1]; // Real copy
arr3[0] = 888;
console.log(arr1[0]); // 999 — original unchanged// ❌ Mistake — JSON not suitable for all data
const arr = [function() {}, undefined, Symbol('id')];
// JSON.stringify(arr); // Works poorly!
// ✅ Correct — use special libraries
// or write your own deep copy function[...arr] — modern way for shallow copy 🆕Understanding the difference between copying and referencing helps avoid errors in programs! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪