Skip to main content
TOPIC 4 OF 8 · 2 MIN READ

Shallow vs. Deep Copy

Understanding the difference between shallow and deep copies is crucial for working with objects and arrays in JavaScript.

Key concepts

Shallow Copy

Copies only the first level of an object or array. Nested structures are shared.

Deep Copy

Creates a completely independent copy, duplicating all levels of the structure.

Examples

Shallow Copy:

const original = { name: 'Alice', address: { city: 'NYC' } };
const shallowCopy = { ...original };

shallowCopy.address.city = 'LA';
console.log(original.address.city); // LA (shared reference)

Deep Copy:

const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.address.city = 'Chicago';
console.log(original.address.city); // NYC (unchanged)

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus