DEV Community

loading...

Discussion on: JavaScript Equality Checks

Collapse
ronakjethwa profile image
Ronak Jethwa Author • Edited

Fun Fact: with nested objects, the nested object property is copied by reference as a property to the new Object.

let user = {
  name: "John",
  sizes: {
    height: 182,
    width: 50
  }
};

let clone = Object.assign({}, user);

console.log(Object.is(user,clone)); //false
console.log(Object.is(user.sizes, clone.sizes)); //true

To avoid this, the easiest way in JavaScript to deep clone an object is

let clone2 = JSON.parse(JSON.stringify(user));
console.log(Object.is(user.sizes, clone2.sizes)); // false