Why in JavaScript, “if ('0' == false)” is equal to false whereas it gives true in “if(0)” statement?

JavascriptWeb DevelopmentFront End Technology

Let’s see the conditions one by one − 

if(‘0’ == false)

It follows the following rule −

If Type(y) is Boolean, return the result of the comparison x == ToNumber(y)

The == does type coercion. This means an explicit type conversion is requested to match the type of the two operands. The left side '0' is converted to a number 0. On comparing the two numbers, and since 0 equals 0, the result is true. In this case, this does not work since it does not implies about the truish/falsy nature of the '0' string, since it got coerced before it was compared.


This checks for the string to be null or empty, not whether it's zero or not. Always remember, a non-empty string is true. No type coercion is used here since strings can be evaluated as truish or falsy on their own merits. 

Published on 03-Feb-2018 15:14:29