Problem with boolean checks in JavaScript

3
var a = '0';
if (!a) console.log('false');
if (a == false) console.log('false 2');

False is not displayed, but false 2 is?

    
asked by anonymous 09.03.2016 / 23:43

1 answer

3

In JavaScript '0' is set to true (anything other than false , 0, "", null , undefined or NaN , is true). Then the first expression denies a true one and therefore does not execute the if command. Until then, okay?

The second is implicitly converting string to numeric (coercion), making the value 0 as operand, a value that is considered false , as shown above. So the comparison is true.

Because in the equality operator the conversion is done and the negation operator does not do the conversion is something that can only be explained with a "defined language".

There are things that only JavaScript does for you. :)

    
09.03.2016 / 23:55