Why if 0 is Equal to False in JavaScript



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.

if(0)

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. 

Updated on: 2020-06-16T13:28:37+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements