MxyL MxyL - 7 months ago 10
Javascript Question

How does Javascript determine whether two objects are the same?

I read over a doc on equality comparison at MDN, but I'm interested in how Javascript performs strict equality checking.

There's also this specification: http://ecma-international.org/ecma-262/5.1/#sec-11.9.6, though, I don't really understand how it applies to two objects. The last statement is the key I think:

Return true if x and y refer to the same object. Otherwise, return false.


But how does Javascript check if they refer to the same object?

For example, given an object
Kitten
that has a
name
property, I create two kitties initialized with their names:

var kittenA = new Kitten("kitty A");
var kittenB = new Kitten("kitty B");


What does Javascript use to determine that that the following statement

kittenA === kittenB


Will return false?

Answer

kittenA and kittenB are both of type object so case 7 applies:

  1. Return true if x and y refer to the same object. Otherwise, return false.

How does the engine know they are two references to the same object? How a reference is implemented exactly will vary per engine. It might just be a number pointing to a memory location or an index in a list (of all objects).