DEV Community

Discussion on: JavaScript Interviews: Create a deep copy of an object

Collapse
jackhpeterson profile image
Jack H. Peterson

This clones, but doesn't deep clone. If you mutate an object nested within source it'll also mutate the target and vice versa.

Collapse
taufik_nurrohman profile image
Taufik Nurrohman • Edited

it'll also mutate the target

That will not happen because the first argument is a new object.

To compare:

// :)
Object.assign({}, source);

// :(
Object.assign(target, source);
Enter fullscreen mode Exit fullscreen mode
Thread Thread
carnicero90 profile image
Filippo Montani

You can pretty straightforwardly check if that's the case by testing it in the console.

Thread Thread
jackhpeterson profile image
Jack H. Peterson • Edited

Objects are passed by reference, not value.

When you clone (assign) an object, it doesn't clone the values of objects within, it clones the reference. Which means both objects, the original and the clone are referencing the same nested objects.

It's a tricky and sometimes frustrating quality of JS. Strings, numbers, bools will clone as expected, but objects will continue to reference the same thing.

Think of assigning a DOM element to a variable. The DOM element still exists, and modifying the variable will still affect the DOM. That's because objects are passed by reference!

Thread Thread
taufik_nurrohman profile image
Taufik Nurrohman

The DOM part makes me get it.