Problem with boolean checks in Javascript

Asked

Viewed 179 times

4

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

Why the false is not displayed but the false 2 is?

  • 1

    If it were 0, the two would appear, but you’re testing string ( '0' ). String to be false needs to be empty. But when you compare with ==, JS converts the string value, and interprets the zero within it.

  • And why does that happen? They both check if my variable is false.

  • 1

    No, one is negation, the other is comparison. Denying a string is different from doing a "cast" and comparing. It’s kind of weird, but it’s a language design problem. If you compare with === it’s gonna get weirder.

  • Always use === unless you’re sure what you’re doing.

1 answer

4


Javascript '0' is defined as true (anything that is not false, 0, "", null, undefined or NaN, is true). So the first expression denies a true one and therefore does not execute the command of the if. So far, so good?

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

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

There are things only Javascript does for you. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.