Course contentsShow
← JavaScript
Lesson 992 of 2,72322. Spread and RestFree lesson

Cloning Arrays and Objects Shallowly

Use spread to create shallow copies of arrays and objects, understanding when this is sufficient.

Cloning Arrays and Objects Shallowly

You'll learn when shallow copying with spread is enough and when it isn't.

You've already seen that spread creates copies of arrays and objects, but now let's understand exactly what gets copied and what doesn't.

What "Shallow" Really Means

A shallow copy duplicates only the top level of a structure. Primitive values (numbers, strings, booleans) are truly copied, but nested objects or arrays are not — only their references are copied. Think of it like photocopying a document that contains a sticky note with an address on it. The photocopy shows the same address, but both copies point to the same house.

// Primitive values — truly independent
const nums = [1, 2, 3];
const copy = [...nums];
copy[0] = 999;
console.log(nums); // [1, 2, 3] — unchanged ✓

// Nested arrays — sharing references!
const nested = [[1, 2], [3, 4]];
const shallowCopy = [...nested];
shallowCopy[0][0] = 999;
console.log(nested); // [[999, 2], [3, 4]] — changed! ⚠️

When Shallow Copying Is Sufficient

Shallow copying works perfectly when:

  • Your data contains only primitives (numbers, strings, booleans)
  • You only need to modify top-level properties
  • You understand the nested references are shared
const user = { name: 'Ali', age: 30 };
const updated = { ...user, age: 31 }; // Perfect! ✓

const settings = { theme: 'dark', notifications: { email: true } };
const changed = { ...settings, theme: 'light' }; 
// Safe — only changing top level ✓

Key Takeaway: Shallow copying with spread is fast and sufficient for flat structures or when you only modify top-level properties, but nested objects/arrays remain shared between the original and the copy.