Shallow copy Vs Deep copy in Javascript
Shallow Copying Objects
An object is said to be shallow copied when the source top-level properties are copied without any reference and there exists a source property whose value is an object and is copied as a reference. If the source value is a reference to an object, it only copies that reference value to the target object.
A shallow copy will duplicate the top-level properties, but the nested object is shared between the original(source) and the copy(target).
Example: Using Object.assign() method
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
Deep copy of object
A deep copy will duplicate every object it encounters. The copy and the original object will not share anything, so it will be a copy of the original.
Example:Using JSON.parse(JSON.stringify(object));
Another Way to Deep clone
function cloneObject(obj) {
var clone = {};
for(var i in obj) {
if(obj[i] != null && typeof(obj[i])=="object")
clone[i] = cloneObject(obj[i]);
else
clone[i] = obj[i];
}
return clone;
}