Throughout learning Javascript, I've read terminologies like Shallow Copy and Deep Copy , and the following question came up:
What is the real difference between Shallow Copy and Deep Copy ?
const moderador = {
nombre : "Gbianchi",
lenguajesFavoritos : ["JavaScript", "Java","PHP"],
esDesarrollador : true,
fechaNacimiento : "2010/01/01"
}
const persona = Object.assign({}, moderador);
persona.nombre = "PabloLozano"
persona.esDesarrollador = false;
persona.lenguajesFavoritos.push("PHP7");
console.info("moderador", moderador );
console.info("persona", persona)
If you represent an object as a graph, you will have a tree where at each node you have a property of that object. Those properties in turn can be objects, thus the depth of the tree grows.
Let's start with a simple object:
It has two properties that store primitive values, so if we were to copy the object to another:
We would have "cloned" the object and we would not have to worry about anything, since the primitive values are immutable.
But what if you
obj1
own an object? Or if this property in turn has other properties that are objects?:This is considered a shallow copy, because we don't replicate each saved value recursively: we've stopped at the first depth level.
The danger of "shallow" copying is that we run into this type of side effect when modifying properties of an object, while thinking that another object is totally independent of what we are doing.
But doing a deep copy can be:
So when we make a copy of an object, we have to choose what kind of copy we need to make. A call to
Object.assign(A, B)
copies to A all existing properties in B, thus giving us a " shallow " copy in a simple way. To make a deeper copy we would need a more complex functionality, in which we can perhaps choose the depth of the copy to perform and if we want to copy functions. If the object is deep but has no loops or functions, we can useBut this will fail in case of encountering loops: