JavaScript doesn’t need presentations; it is an awesome language. If you have been working with it, you probably have noticed some weird behaviors. Once of them is Deep Copy, let’s take a look at this interesting concept
When we do a variable copy JavaScript create a new memory slot and there, is saving the value copied, then the new variable point to this new memory slot. For example:
x = 5;
y = x;
y is pointing to a new memory slot, which have the same value of x, it means, 5. Visually it would be something like this:
What we see before applies only to primitives values, for objects is different. Imagine we have the follow two objects
let a = {
name: 'Rick',
lastName: 'Sanchez',
};
let b = a;
In before code b doesn’t have its own memory slot as we could expect, instead of that, b is pointing to memory slot where a is saved
What problems could this behaviour cause? Basically, if you change any field of a or b, both variables will changed. Copy the follow code and verify by yourself
let a = {
name: 'Rick',
lastName: 'Sanchez',
};
let b = a;
b.name = 'Morty';
console.log('a: ', a); // a: { name: 'Morty', lastName: 'Sanchez' }
console.log('b: ', b); // b: { name: 'Morty', lastName: 'Sanchez' }
The solution for this? We need to do a deep copy to save the value of a in a new independent memory slot where b will be pointing
const b = JSON.parse(JSON.stringify(a));
In this way, we are forcing JavaScript to create a new memory slot by changing the format from Object to JSON, this is done using the stringify method, then the JSON with its own slot becomes into Object again with parse method, so both variables remain totally independent.
Top comments (0)