4

Possible Duplicate:
Why [] == [] is false in javascript?

I would like to ask about strange thing, i.e.:

var x = "pl";
var y = ["pl"];
[x] == y; // false - why?
x == y; // true - how ? 
x === y; // false - okay

Can some one explain it?

Thanks in advance.

Community
  • 1
  • 1
cojack
  • 2,444
  • 1
  • 17
  • 18

3 Answers3

4

The first one is false because you're comparing two arrays (which are objects) - a comparison which will always be false unless the objects are actually the same object, or if the objects are coerced to a different type of value like in the second comparison.

In the second comparison, y is coerced to be a string value, and then found to be equal to "pl".

For instance, this code:

["pl"] + "foo" → "plfoo"

Incidentally, this is why you should always use === instead of == - it doesn't result in any surprising coercions. That's why the third comparison is false.

jonvuri
  • 5,738
  • 3
  • 24
  • 32
2

Array to Array (abstract equality comparison)

[x] == y; // false - why?

[x] and y do not refer to the same object. Arrays are objects and the == operator tests that they are the same object, not simply two objects having identical values for all properties. In order to determine object-equality in that way, you'll have to manually enumerate the properties of each object and test each value.

According to The Abstract Equality Comparison Algorithm used by ==:

Return true if x and y refer to the same object. Otherwise, return false.

String to Array (abstract equality comparison)

x == y; // true - how ? oO

y, an array, is coerced into a string because you used == when comparing it to x, a string.

According to The Abstract Equality Comparison Algorithm used by ==:

If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).

String to Array (strict equality comparison)

x === y; // fasle - okey

===, unlike ==, will not coerce y into a string... so, you're comparing a string to an object.

According to The Strict Equality Comparison Algorithm used by ===:

If Type(x) is different from Type(y), return false.

canon
  • 40,609
  • 10
  • 73
  • 97
0
[x] == y; 

['pl'] == ['p1'] - comparing refs on 2 different arrays in memory

x == y; 

The same as "pl" == ["p1"].toString(). JS convert the second argument to the string because the first one is also string

CruorVult
  • 823
  • 1
  • 9
  • 17