Cloning explained visually

Having seen how easy it is to cause unintended mutations, the next question is: how do we prevent this?

The solution is cloning. We construct an identical object or array, with all of the same properties. Then, if we need to make any changes, we can do it on the clone, leaving the original untouched.

I always opt for the spread syntax:

const jsBook = { title: 'JavaScript for dummies', publisher: 'Penguin Books' };
const clone = { ...jsBook };

// and it’s easy to override specific properties:
const pythonBook = { ...jsBook, title: 'Python for dummies' };

The 3 internal steps to cloning

Let’s understand exactly what happens when we duplicate an array or object. Note: we are looking down on top of an array-submarine ship, from a birds-eye perspective.