Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

I know that === is typically referred to as the identity operator. Values being compared must be of the same type and value to be considered equal. Then why below line returns false?

Array("asdf") === Array("asdf")

like image 764
Om3ga Avatar asked Dec 07 '12 04:12

Om3ga


2 Answers

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.

like image 189
Eli Avatar answered Oct 05 '22 22:10

Eli


First of all === is strict equality, not an identity operator, and Arrays, like objects are reference objects, not value objects as in the case of numbers and strings...

So when you are comparing those 2 arrays, you are creating two different arrays in memory. It'd be the same as saying...

var x = { a: 1 }; 
var y = { a: 1 };

x === y; //false  

You can't directly compare arrays or objects like that.

like image 31
jcreamer898 Avatar answered Oct 05 '22 22:10

jcreamer898