0

I got some empty arrays below and after I compare them the results are all false.

var a = new Array();
var aa = new Array();
var b = [];
var bb = [];
document.write(a == b);     // false
document.write(a == aa);    // false
document.write(b == bb);    // false

To the first comparison (a==b) I can somewhat find the answer in this page, but for other two I just can't figure out why. Can someone help me?

Community
  • 1
  • 1

1 Answers1

0

The answer is the same in all cases. Either you use this new Array[] or this [], a new array would be created and the reference to this array would be stored to the variabe on the left. That being said, in your case you create 4 arrays. So you have for different references to them in the variables a, aa, b and bb. That's the reason all the expressions you mentioned are evaluated as false. The equals operator doesn't compare the items in the arrays just the references to them.

Let's consider the following snippet. Since arrayA, arrayB and arrayC contains a reference to the same array, when you push items to arrayC and you output to the console the arrays you would see the same contents.

var arrayA = [];
var arrayB = arrayA;
var arrayC = arrayB;

// Apparently this evaluate to true.
console.log(arrayC == arrayA);

arrayC.push(1);
arrayC.push(2);
arrayC.push(3);
arrayC.push(4);

console.log(arrayA);
console.log(arrayB);
console.log(arrayC);
Christos
  • 50,311
  • 8
  • 62
  • 97