Shallow vs. Deep Copy
Topic 4JavaScript Part 5 (Important Keywords)
Shallow vs. Deep Copy
Introduction
Understanding the difference between shallow and deep copies is crucial for working with objects and arrays in JavaScript.
Key Concepts and Definitions
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)Interview guide discussion
(0)Join the discussion — login to comment and help other developers.
Login to comment