In JavaScript almost everything is an Object. There are primitive types which auto-box between primitive and Object version as needed.
When you compare Objects in JavaScript, you are actually comparing if they are the same reference(e.g point to the same memory address). Proof here
var a = [1, 2, 3];
b = a;
b.push(5);
console.log(a); // 1, 2, 3, 5
In this case a == b
or a === b
will yield true
. If I want to compare two separate arrays, then I need to loop through them and compare element by element.
In the following case, I can use a trick though. Live demo
var x = [1, 2, 3];
var y = [1, 2, 4];
var z = [1, 2, 3];
var equals = x.join("").localeCompare(y.join("")) == 0; //x with y
var equals2 = x.join("").localeCompare(z.join("")) == 0; //x with z
document.body.innerHTML += equals + "<br />";
document.body.innerHTML += equals2 + "<br />";
In your weird case
Array([],null,undefined,null) == ",,,";
In JavaScript the ==
operator will perform all the type casts/conversions it can perform to check for equality. It will try to compare a String
with String
, at which point the left hand side, the Array
will be converted to a String
using a simple toString()
call!
Look here, I guess the answer is now obvious.