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.
A CRAZY LOVER of Codes and Programming, INSANELY in love with TypeScript, aiming to be my CRAZIEST Version!!! Wanna create CRAZIEST things and change the WORLD!!
Location
Kameswar, Dharmanagar, (North) Tripura, (NorthEast) India
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
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.Oh, thank you sooo much Sir @jamesthomson for pointing this out. Really appreciate it. Updated the blog