DEV Community

Daniel Nieto
Daniel Nieto

Posted on

Deep copy in JavaScript, what is that?

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;
Enter fullscreen mode Exit fullscreen mode

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:

x point to A2 address and y point to A3 address

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;
Enter fullscreen mode Exit fullscreen mode

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

variables a and b point to same A8 address

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' }
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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)