Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do alert(!!"0") and alert(false == "0") both output true in JavaScript

Tags:

javascript

As far as I know in JavaScript !! is supposed to normalize a boolean value converting it to true or false from some other type. This would mean that the "0" converts to boolean true. On the other hand if I compare it with false it turns out that it is in fact false (as the result of the comparison is true). What rule am I missing here. I have tested it in IE and Opera.

like image 510
Stilgar Avatar asked Dec 31 '10 00:12

Stilgar


People also ask

Why True == true is false in JS?

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; else if either operand is a string, the other operand is converted to a string if possible.

How do you know if JavaScript is true or false?

Use the strict equality (===) operator to check if a variable is equal to false - myVar === false . The strict equality operator will return true if the variable is equal to false , otherwise it will return false . Copied!


3 Answers

The == operator checks for loose equality, which has nothing to do with truthiness.

Specifically, it will convert to operands to numbers, then compare the numbers.
Strings containing numbers convert to the numbers that they contain; booleans convert to 0 and 1.
Objects are converted by calling valueOf, if defined.

Thus, all of the following are true:

  • "1" == 1
  • "0" == false
  • "1" == true
  • "2" != true
  • "2" != false
  • ({ valueOf:function() { return 2; } }) == 2
  • ({ valueOf:function() { return 1; } }) == true
like image 196
SLaks Avatar answered Nov 09 '22 01:11

SLaks


In the first case, a non-empty string is equivalent to true.

In the second case, because one operand is a boolean, both operands are converted to numeric values. I believe false converts to the numeric value 0 and the string "0" also converts to a numeric 0, resulting in 0 == 0 which is true.

Check out the Mozilla reference for operator behavior.

like image 21
Jonathon Faust Avatar answered Nov 09 '22 00:11

Jonathon Faust


For the first expression, section 9.2 of ECMA-262 defines an abstract operation ToBoolean internally used by the logical NOT operator. It says:

String
The result is false if the argument is the empty String (its length is zero); otherwise the result is true.

For the second expression, JavaScript will perform type coercion when it attempts to compare these values of different data types. Douglas Crockford says that this is a misfeature. It would be false if you had used === instead of ==. The rules are rather complex, so you should directly look in section 11.9.3 of ECMA-262 for the details.

like image 39
PleaseStand Avatar answered Nov 08 '22 23:11

PleaseStand