← Back to all posts

Shallow Copy vs Deep Copy in JavaScript (Explained Like You're Five)

Have you ever copied something in JavaScript… changed one small thing… and suddenly your original data also changed?

If yes, then you're welcomed to the Shallow Copy vs Deep Copy problem. When I first learned JS, this concept confused me so badly that I felt JS was betraying me. So I finally sat down, understood, and here's the simplest explanation you'll ever find.

Let's start with the "What" question.

What Does "Copying" Even Mean?

If someone asks you to "copy" your homework, you'll probably create a new page, right?

But in JavaScript, copying works differently. When you copy an object or an array, JavaScript doesn't always create a new copy. Sometimes it just points to the original one. Because both original and copy point to the same object in memory.

Real Shallow Copy Methods in JavaScript

These create a new object/array… but only the top-level values are copied.

Array shallow copies


const arr = [1, 2, 3];
const shallow = [...arr]; // OR arr.slice();
  

Object shallow copies


const obj = { a: 1, b: 2 };
const shallow = { ...obj }; // OR Object.assign({}, obj);
  

But the trap:

If the object contains nested objects, those nested ones are STILL shared.


const user = {
  name: "Ankit",
  hobbies: ["coding", "gaming"],
};

const shallowCopy = { ...user };
shallowCopy.hobbies.push("fitness");

console.log(user.hobbies); // ["coding", "gaming", "fitness"] 😱
  

Because inside the object, hobbies is still the same array.

Deep Copy in JavaScript

A deep copy makes a completely new object. Nothing is shared. Changes in the copy never affect the original.

  • Shallow copy → copies reference
  • Deep copy → copies actual value

The Spread operator (...) is shallow. If you want a deep copy, modern JavaScript gives us a built-in method for this:


const deepCopy = structuredClone(user);
  

structuredClone() is the best deep copy method.

If your nested data is changing unexpectedly → you made a shallow copy by mistake.

Lastly…

If you are learning JavaScript, you will face bugs caused by shallow copying. I faced them too. Everyone does.

But once you understand the difference between shallow and deep copy, your debugging will become easier, your code becomes cleaner and JS starts to make sense.

This article is not just for readers, it helped me understand the topic too. Two birds, one stone.

← Back to all posts