Learn the concept
Objects & Copying
A shallow copy duplicates only top-level properties while nested objects share references; a deep copy recursively duplicates all nested objects creating fully independent copies.
Shallow Copy:
Methods that create shallow copies:
{...obj}, [...arr])Object.assign({}, obj)Array.prototype.slice()Array.from()Deep Copy:
Methods for deep copy:
structuredClone() (Recommended - HTML spec, widely supported)
JSON.parse(JSON.stringify()) (Legacy)
lodash _.cloneDeep() - Most comprehensive, handles edge cases
const original = {
name: 'John',
address: { city: 'NYC', zip: '10001' }
};
// Shallow copy with spread operator
const shallow = { ...original };
// Modifying top-level works as expected
shallow.name = 'Jane';
console.log(original.name); // 'John' - unchanged
// But nested objects are shared!
shallow.address.city = 'LA';
console.log(original.address.city); // 'LA' - original mutated!
// Same issue with Object.assign
const shallow2 = Object.assign({}, original);
shallow2.address.zip = '90001';
console.log(original.address.zip); // '90001' - mutated again!Creating shallow copies of state slices before modifying nested properties to maintain immutability in reducers
Storing deep copies of application state at each step for history navigation and state snapshots
Cloning base request configurations before adding endpoint-specific options like headers or query params
Build a text editor state manager using structuredClone to create history snapshots for undo and redo
Build a function that compares two objects recursively and returns the differences as a structured report
Provides immutable state updates using a draft proxy pattern instead of manual shallow/deep copying
Uses Immer internally so reducers can write mutating logic that automatically produces immutable updates