Question about indexOf

How come this works:

const courses= [
    {
        "name": "React",
        "id": 1
    },
    {
        "name": "Node.js",
        "id": 2
    },
    {
        "name": "Redux",
        "id": 3
    }
]

const course = courses.find(c => c.id === 3)
    
const index = courses.indexOf(course)
console.log(index) // output: 2

But this won’t

const courses= [
    {
        "name": "React",
        "id": 1
    },
    {
        "name": "Node.js",
        "id": 2
    },
    {
        "name": "Redux",
        "id": 3
    }
]
    
const index = courses.indexOf({"name": "Redux", "id": 3})
console.log(index) // output: -1

This is making a new object and looking for it in the array:

container.indexOf({ name: 'b', value: 10 })

Also:

course === {"name": "Redux", "id": 3}
false

You are trying to use an object like a primitive value, but objects are compared by reference not by value.

1 Like