Triple equal signs return false for arrays in javascript. why?

They are not equal because a new array is being created in each of these statements, each being a brand new array object with just identical contents. If you create two new objects:

var a = {};
var b = {};

a === b // false

When you create new objects, arrays, functions, etc., a brand new object is placed into memory. Creating a new object with the same internals as another object will not magically cause that object to point to one that already exists. The objects may look the same, but they do not point to the same instance. Now if your statement had been like so:

var arr = ['asdf'];

arr === arr; // true

This is obviously be true. === is strict equality, not an identity operator. When objects are ran through a strict equality operator, they are checked to see if they point to the same reference. As I explained earlier, each time you use new Array or [] that a brand new object will be created, each being a new and different reference. So there is no way that two arrays, or any object, can come out === being true unless they point to the exact same array. Just because two objects are being created with identical contents does not mean that they point to the same object, just two identical, but different objects.

Think of constructing functions:

var Car = function (color) {
    this.color = color;
};

var ford = new Car('green');
var chevy = new Car('green');
var toyota = ford;

ford === chevy // false

Just because you are using the same constructor does not mean that every time you call it the same object gets returned. Rather, a new object will be returned every time. Just because both cars are green doesn’t mean it’s the same car.

ford === toyota // true

This is now true because both variables point to the exact same Car reference.

Leave a Comment