Reputation: 267
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:
object1
and object2
are not the sameobject3
and object4
are the sameobject5
and object6
are not the sameCan 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
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