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
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
Share Improve this question edited Nov 5, 2013 at 13:31 Saturnix 10.6k18 gold badges68 silver badges126 bronze badges asked Nov 5, 2013 at 13:31 FokerFoker 1,0113 gold badges10 silver badges22 bronze badges 05 Answers
Reset to default 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.
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 pare 1
and [1]
, there needs to be type juggling involved.
Arrays can be cast to a string, by joining all items with a ma. This results in the string "1"
.
In turn, "1"
can be cast to a number, giving 1
. 1 == 1
is clearly true.
please see here: How to pare arrays in JavaScript?
the []
syntax is a literal constructor for Array objects, and objects cannot be pared to others (well they can, with negative result).
Strings and numbers are immutable in JavaScript, so you're literally paring 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.
Because arrays are objects and they are pared 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