Topic 19 of 37
structuredClone
Overview
When you want to duplicate an object or array without affecting the original, you must copy it. A Shallow Copy duplicates the top level, but nested objects are still passed by reference. A Deep Copy creates an entirely independent clone of the original, including all nested structures.
Syntax
The spread operator only copies the first level. The 'address' object inside is still shared.
Shallow Copying
javascript
const original = { name: "Alice", address: { city: "Paris" } };
// Shallow copy using Spread Operator (...)
const shallow = { ...original };
shallow.name = "Bob"; // Original name is safe
shallow.address.city = "London"; // Original address is MODIFIED!
console.log(original.address.city); // "London"structuredClone() is a built-in function that creates a true deep copy. Before this, developers used JSON.parse(JSON.stringify(obj)), which couldn't handle Dates, Maps, Sets, or functions.
Deep Copying with structuredClone
javascript
const original = { name: "Alice", address: { city: "Paris" } };
// Modern Native Deep Copy (ES2022)
const deep = structuredClone(original);
deep.address.city = "London";
console.log(original.address.city); // "Paris" (Safe!)Common Pitfalls
- Using JSON.parse(JSON.stringify()) to deep clone an object containing 'undefined' or a Date object will result in missing keys or stringified dates.
Interview Tips
- If asked to write a custom deep clone function in an interview, use recursion to traverse keys and copy them if they are typeof 'object'.
Real-World Example
Duplicating a complex form state so the user can 'Cancel' and revert to the original state.
example
javascript
// Save original state deeply
const initialState = structuredClone(formState);
// On Cancel
function onCancel() {
setFormState(initialState);
}