Deep Cloning with JSON
You'll learn how to create quick deep copies of objects using JSON methods and when this technique falls short.
The Core Idea
When you assign an object to a new variable, JavaScript only copies the reference—not the actual data. If you need a true independent copy, including nested objects, you can combine JSON.stringify() and JSON.parse() to create a deep clone.
The pattern looks like this:
const original = {
name: 'Alice',
address: {
city: 'Boston',
zip: '02101'
}
};
const clone = JSON.parse(JSON.stringify(original));
clone.address.city = 'New York';
console.log(original.address.city); // 'Boston' — unchanged!
console.log(clone.address.city); // 'New York'
How It Works
Think of it like creating a blueprint: JSON.stringify() converts your object into a JSON string (a text snapshot), then JSON.parse() rebuilds a completely new object from that string. Because it's reconstructed from scratch, there are no shared references.
Important Limitations
This technique has blind spots—it can't handle:
- Functions (they disappear)
- undefined values (omitted from output)
- Symbols (excluded)
- Dates (become strings)
- Circular references (throw errors)
const obj = {
func: function() {},
undef: undefined,
date: new Date()
};
const copy = JSON.parse(JSON.stringify(obj));
console.log(copy); // { date: '2024-...' } — func and undef are gone!
Key Takeaway: JSON.parse(JSON.stringify(obj)) provides a quick deep clone for simple, serializable objects, but fails with functions, undefined values, Symbols, Dates, and circular references.