Back

Imagine you're an architect and you've designed a blueprint for a house. This blueprint is detailed and contains references to all the elements of the house like doors, windows, and furniture. Now, suppose you want to create another house based on this original blueprint but with some variations.

Shallow Cloning: Photocopying the Blueprint

Shallow cloning is like taking a photocopy of your original blueprint. This photocopy will have all the main points of the original blueprint, but it's just a surface copy. This means:

Deep Cloning: Creating a Custom Blueprint

Deep cloning, on the other hand, is like creating a brand new blueprint based on the original. This process involves:

In JavaScript

Translating this back to JavaScript:

let original = { color: "blue", furniture: { chair: "wooden" } };
let shallowClone = Object.assign({}, original); // We could also use the spread operator: {...original}
shallowClone.furniture.chair = "plastic"; // This changes the chair for both original and clone
let original = { color: "blue", furniture: { chair: "wooden" } };
let deepClone = JSON.parse(JSON.stringify(original)); // We can also use `structuredClone`
deepClone.furniture.chair = "plastic"; // This changes the chair only in the clone

Performance

Continuing with our analogy, imagine you have two construction teams tasked with building houses based on the blueprints (our cloned objects) from the earlier example.

Shallow Cloning: Quick Setup Team

The team working with a shallow clone (the photocopy of the original blueprint) has a straightforward task. They only need to build the outer structure of the house according to the new blueprint. The detailed interior elements like furniture are not remade; they simply refer to the existing items cataloged for the original house. This means:

Deep Cloning: Custom Build Team

On the other hand, the team working with a deep clone (the entirely new custom blueprint) must build everything from scratch. Every piece of furniture and every interior detail must be crafted anew, according to the specifications of the new blueprint. This involves: