3

in JavaScript:

(1 == 1) === true;
(1 === 1) === true;

and

var a = 1;
var b = [1];
(a == b) === true

but

([1]==[1]) === false;

Why is it so? I have no idea

Saturnix
  • 10,130
  • 17
  • 64
  • 120
Foker
  • 944
  • 2
  • 9
  • 22

5 Answers5

13

[1] and the other [1] are different objects, and object equality is defined as identity. In other words, an object is only equal to itself.

> a = [1]
[1]
> b = [1]
[1]
> a == b
false
> b = a
[1]
> a == b
true

Reference: http://es5.github.io/#x11.9.3, step 1.f is what applies here.

georg
  • 211,518
  • 52
  • 313
  • 390
6

Because [1] and [1] are two instances of the Array object. As such, they are not equal (two objects are equal only if they are the exact same instance).

However, when you compare 1 and [1], there needs to be type juggling involved.

Arrays can be cast to a string, by joining all items with a comma. This results in the string "1".

In turn, "1" can be cast to a number, giving 1. 1 == 1 is clearly true.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

Because arrays are objects and they are compared by reference rather than value so only the same instances are equal

For example:

var array1 = [1];
var array2 = array1;
(array1 == array2) === true;
(array1 == [1]) === false
Rob Willis
  • 4,706
  • 2
  • 28
  • 20
0

please see here: How to compare arrays in JavaScript?

the [] syntax is a literal constructor for Array objects, and objects cannot be compared to others (well they can, with negative result).

Community
  • 1
  • 1
bukart
  • 4,906
  • 2
  • 21
  • 40
0

Strings and numbers are immutable in JavaScript, so you're literally comparing the content of a certain block in memory with itself when you do something like "string" === "string" or 1 === 1, whereas you're constructing a new Array object each time you use the constructor.

I hope this makes sense.

holographic-principle
  • 19,688
  • 10
  • 46
  • 62