Anshu
Anshu

Reputation: 7853

javascript comparison crises

I came across the following and was unable to grasp the reason, can anyone explain please?

var foo = [0];
console.log(foo == !foo); // true 
console.log(foo == foo);  // true

Upvotes: 4

Views: 131

Answers (2)

bfavaretto
bfavaretto

Reputation: 71908

The second comparison is simple to explain: foo is equal to itself.

The first one, however, is a bit tricky: foo is an array, which is an object, which evaluates to true when coerced to boolean. So !foo is false. But foo on the left side of the comparison is not being converted to boolean. Both operands are actually converted to numbers during the equality comparison. This is how it evaluates:

[0] == false
[0] == 0
"0" == 0
0 == 0
true

According to MDN, on comparisons with the equality operator ==:

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible

I know this explanation sounds superficial. It's actually much more complicated than that, but the basic steps are the ones I listed above. You can see the details on the ECMA-262 specification, particularly on sections 9 and 11.9.

Upvotes: 6

Related Questions