HomeJAVASCRIPTHow do you clone an array?

How do you clone an array?

In JavaScript, cloning (copying) an array means creating a new array with the same elements, without referencing the original one. There are several ways to do this:


🔹 1. Using spread operator (...)

let arr = [1, 2, 3];
let clone = [...arr];

console.log(clone); // [1, 2, 3]

✅ Creates a shallow copy (nested objects/arrays are still referenced).


🔹 2. Using slice()

let arr = [1, 2, 3];
let clone = arr.slice();

console.log(clone); // [1, 2, 3]

✅ Also makes a shallow copy.


🔹 3. Using Array.from()

let arr = [1, 2, 3];
let clone = Array.from(arr);

console.log(clone); // [1, 2, 3]

🔹 4. Using concat()

let arr = [1, 2, 3];
let clone = [].concat(arr);

console.log(clone); // [1, 2, 3]

🔹 5. Using structured cloning (deep copy)

If your array has nested objects/arrays and you want a deep copy, use:

let arr = [1, [2, 3], {a: 4}];
let clone = structuredClone(arr);

console.log(clone); // [1, [2, 3], {a: 4}]
console.log(arr[1] === clone[1]); // false (different references)

⚠️ Shallow vs Deep Copy

  • Shallow copy: copies only the top-level elements. If array has objects/arrays inside, they are still referenced.
  • Deep copy: copies everything recursively, creating entirely new objects/arrays.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *