RinnieR
RinnieR

Reputation: 267

Why is an object different than the same object destructured?

I was working with a library that needs a configuration object with a couple of properties inside of it... I realized that {...object} is not the same as object, I tried to understand why but even after debbuging and logging those objects, I can't see not difference at all on them:


const configurationObject = {
  name: 'name',
  uniqueId: 'random-string'
}

//...

const object1 = configurationObject
const object2 = {...configurationObject}

console.log(object1 == object2) // false

const object3 = configurationObject
const object4 = configurationObject

console.log(object3 == object4) // true

const object5 = {...configurationObject}
const object6 = {...configurationObject}

console.log(object5 == object6) // false

I just realized that:

  1. object1 and object2 are not the same
  2. object3 and object4 are the same
  3. object5 and object6 are not the same

Can someone explain why that happens? I tought about it being related to different memory adresses, but that wouldn't make much sense since object5 and object6 are not the same also.

Also, if that's related to memory address, can someone tell me how to access, via node, the memory address? Or at least something that tells me both objects are different.

Upvotes: 1

Views: 43

Answers (1)

Andrew Parks
Andrew Parks

Reputation: 8107

Doing object1 === object2 does not check if the two variables reference objects that contain the same properties. It checks if both variables reference the same object instance.

The line const object2 = {...configurationObject} creates a new object instance containing a shallow copy of the properties in object1. Therefore, it is a different object instance.

const configurationObject = {
  name: 'name',
  uniqueId: 'random-string'
}

//...

const object1 = configurationObject
const object2 = {...configurationObject}

console.log(object1 === object2) // false
console.log(JSON.stringify(object1) === JSON.stringify(object2)) // true

const object3 = configurationObject
const object4 = configurationObject

console.log(object3 === object4) // true
console.log(JSON.stringify(object3) === JSON.stringify(object4)) // true

const object5 = {...configurationObject}
const object6 = {...configurationObject}

console.log(object5 === object6) // false
console.log(JSON.stringify(object5) === JSON.stringify(object6)) // true

Upvotes: 1

Related Questions