DEV Community

Discussion on: JavaScript Object Trap Simplified by SilvenLEAF

Collapse
 
jamesthomson profile image
James Thomson

There's a few things here that are a bit misleading...

In your "shallow clone" example, you aren't really cloning anything. You are simply creating a new variable and assigning an existing object to that variable by reference. So when you say

But, if I changed one and it changed the other, this cloning will be called Shallow cloning because they are cloned from the outside but are same from the inside. They both are the same object.

You haven't actually performed a shallow clone, just assigned an existing reference to a new variable.

  • A shallow clone is when you actually create a new object based on another, but any nested objects within that clone maintain their reference. So, your example let objectB = { ...objectA }; is considered a shallow clone.

  • A deep clone will clone the entire contents of an object so that it is truely a unique clone and therefore maintains no references from the source object. Your example with JSON.stringify is one method and is acceptable in some use cases, however it's not a foolproof method as it will destroy nested functions within the object. To truely perform a deep clone, you have to loop through the objects contents, see Lodash for an example on this.

Collapse
 
silvenleaf profile image
SilvenLEAF • Edited

Oh, thank you sooo much Sir @jamesthomson for pointing this out. Really appreciate it. Updated the blog