Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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" == 00 == 0true

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.

Solution 2:

You should use "===" and "!==" instead of "==" and "!=" More explanations there: Which equals operator (== vs ===) should be used in JavaScript comparisons?

http://net.tutsplus.com/tutorials/javascript-ajax/the-10-javascript-mistakes-youre-making/

Post a Comment for "Javascript Comparison Crises"