0
0
JavascriptHow-ToBeginner · 3 min read

How to Copy Array in JavaScript: Simple Methods Explained

To copy an array in JavaScript, you can use the spread operator like let copy = [...original], or use slice() method like let copy = original.slice(). Both create a new array with the same elements, avoiding changes to the original array.
📐

Syntax

Here are common ways to copy an array in JavaScript:

  • Spread operator: let copy = [...original] creates a new array by spreading elements.
  • Slice method: let copy = original.slice() returns a shallow copy of the array.
  • Array.from: let copy = Array.from(original) creates a new array from an iterable or array-like object.
javascript
let original = [1, 2, 3];

// Using spread operator
let copy1 = [...original];

// Using slice method
let copy2 = original.slice();

// Using Array.from
let copy3 = Array.from(original);
💻

Example

This example shows how to copy an array and modify the copy without changing the original array.

javascript
const original = ['apple', 'banana', 'cherry'];

// Copy using spread operator
const copy = [...original];

// Change the copy
copy.push('date');

console.log('Original:', original);
console.log('Copy:', copy);
Output
Original: [ 'apple', 'banana', 'cherry' ] Copy: [ 'apple', 'banana', 'cherry', 'date' ]
⚠️

Common Pitfalls

One common mistake is assigning an array directly, which copies only the reference, not the array itself. This means changes to the new variable affect the original array.

Example of wrong and right ways:

javascript
// Wrong way: copies reference
const original = [1, 2, 3];
const copyWrong = original;
copyWrong.push(4);
console.log('Original after wrong copy:', original); // original changed

// Right way: copies array
const copyRight = [...original];
copyRight.push(5);
console.log('Original after right copy:', original); // original unchanged
Output
Original after wrong copy: [ 1, 2, 3, 4 ] Original after right copy: [ 1, 2, 3 ]
📊

Quick Reference

MethodDescriptionExample
Spread operatorCreates a shallow copy by spreading elements`let copy = [...original]`
Slice methodReturns a shallow copy of the array`let copy = original.slice()`
Array.fromCreates a new array from iterable or array-like`let copy = Array.from(original)`

Key Takeaways

Use the spread operator or slice() to create a new copy of an array.
Assigning an array directly copies the reference, not the array itself.
Copied arrays are shallow copies; nested objects remain linked.
Modifying the copy does not affect the original array.
Array.from() is another way to copy arrays or array-like objects.