-1

I am going through a professional book in JavaScript and came to an example of indexOf that confuses me. Please see below.

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

var morePeople = [person];
alert(people.indexOf(person)); //returns -1 
alert(morePeople.indexOf(people)); //returns 0

I am wondering why the first alert returns -1,because people contains the name Ali. I am confused!

Celaro
  • 196
  • 1
  • 7
  • 19

2 Answers2

1

JavaScript equality checks on objects test to see if they are the same object, not if they are identical objects.

{name: "Ali"} != {name: "Ali"}

It contains the name Ali, but it is not the same object.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Objects are only the same if they reference the same object, not when they happen to have the same properties and values, but were defined separately.

These two objects are not the same:

a = { test: 1 };
b = { test: 1 };
// now a !== b

The array is not really the aspect that matters here: both peopleand morePeople are arrays. The core of your issue is why the objects that are first elements of each of these two arrays are not the same object. Primitive values are considered the same when they have the same value:

a = 1
b = 1
// now a === b
a = 'test'
b = 'test'
// again a === b

But this is in general not true for objects, as they represent references. The rules for equality are more complex (see this Q&A for example), and they play a role when you apply .indexOf().

Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286
  • So that implies that it sees person as an object and people as an array of object and therefore they are not equal? Thank you – Celaro Oct 08 '16 at 23:00
  • No, the fact that arrays are involved is not the issue here. The reason is that you create twice an object and thus they are not the same. See the addition to my answer. – trincot Oct 09 '16 at 07:35
  • I understand now, thank you! – Celaro Oct 11 '16 at 06:42