1

I have the following code:

var person = { name: "Nicholas" };
var people = [{ name: "Nicholas" }];
var morePeople = [person];

alert(people.indexOf(person)); //-1
alert(morePeople.indexOf(person)); //0

I can't figure out why first alert gives -1 (not found) when people is an array and contains { name: "Nicholas" }

3
  • 4
    Because two different object "instances" are never equal to each other. Commented Feb 2, 2016 at 21:48
  • 2
    You created two different objects. They just happen to share the same string value, but not the same value themselves. Commented Feb 2, 2016 at 21:49
  • stackoverflow.com/questions/1068834/… Commented Feb 2, 2016 at 21:50

1 Answer 1

4

Because while both objects contain the same information, they aren't the same object. For example:

var nick = { name: 'Nick' };
var nick2 = { name: 'Nick' };
console.log(nick === nick2); // false
console.log(nick === nick); // true

This is true because Javascript doesn't do per-property comparisons between objects to determine equality. It only checks "is this literally the exact same object as the other one?" If, and only if, that is true will you get a true result when comparing two objects.

.indexOf uses such comparisons to determine if any object or value is in an array.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.