Deep copy Shallow copy javascript

Md.Al-Amin Sahed
2 min readAug 18, 2022

Copy is the same value as anything. But copy value and the original value have individual independence. That means if the copy value is changed, the original value doesn’t change according to the copy value.

Deep copy: Deep copy copies the value of the original value and disconnects with the original value. A deep copy copies the old value and allocates a different memory location for the new copy. Then assign the old value to the new variable or object.

Now, if we change the value of b=6, then the value of a is not changed.

If we change the value of a, then the value of b is not changed.

Shallow copy: Shallow copy means a new value is connected to the original value. In memory, the new object has stored the location of the original object. This is the reason, the copy object and original object are dependent on each other. If the state of the copy or original object is changed, it reflects in both.

Now, look at the above code. When we change the value of a.name, b.name is also changed. This is the shallow copy.

Think for a couple of minutes, what if we changed the value of b.name, what is happened to the a.name. Is it changed or not?

Shallow copy is like nibba/ nibbi lovers. If you hit one, another one also feels the pain 😁.

Now, the big question is how to deep copy an object? Spread operator in JavaScript saves you in this situation.

But there is a little problem with nested objects.

This behaves like a shallow copy. Now how to solve this problem?

Huuh! We solved nested object problems like this.

Originally published at https://sahedthought.hashnode.dev.

--

--