-2

On line 9, collection[2] does equal source, but the resulting if statement logs 'sorry not found'. Why doesn't it log Object.keys(source) instead?

const collection = [
    {id: 1, name: 'A'},
    {id: 2, name: 'B'},
    {id: 3, name: 'C'}
]

const source = {id: 3, name: 'C'}

if (collection[2] == source) {
    console.log(Object.keys(source))
} else {
    console.log('sorry not found')
}
  • 5
    Objects are compared using their reference - not by their key-value pairs as you probably expect. Although the key-value pairs are same, `collection[2]` and `source` hold references to two different objects; that is why they are not equal. – Yousaf Dec 08 '21 at 09:37

1 Answers1

1

Objects are reference types so you can’t just use === or == to compare 2 objects. Instead try this:

const collection = [
    {id: 1, name: 'A'},
    {id: 2, name: 'B'},
    {id: 3, name: 'C'}
]

const source = {id: 3, name: 'C'}

if (JSON.stringify(collection[2]) === JSON.stringify(source)) {
    console.log(Object.keys(source))
} else {
    console.log('sorry not found')
}
Arif Khan
  • 508
  • 5
  • 12