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" }

Shepherd
  • 273
  • 1
  • 2
  • 12

1 Answers1

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.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91