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

JavaScript's comparison behavior can be confusing when mixing different data types. Let's examine why '0' == false returns true while if(0) evaluates to false.

Understanding '0' == false

When using the loose equality operator ==, JavaScript performs type coercion following specific rules:

console.log('0' == false);  // true
console.log(typeof '0');    // "string"  
console.log(typeof false);  // "boolean"
true
string
boolean

The comparison follows this rule: If Type(y) is Boolean, return the result of the comparison x == ToNumber(y)

Here's what happens step by step:

// Step 1: Convert boolean false to number
console.log(Number(false));  // 0

// Step 2: Compare '0' == 0 (string vs number)
// String '0' gets converted to number 0
console.log(Number('0'));    // 0

// Step 3: Compare 0 == 0 (both numbers)
console.log(0 == 0);         // true
0
0
true

Understanding if(0)

The if statement checks truthiness without type coercion. It evaluates the value directly:

if (0) {
    console.log("This won't run");
} else {
    console.log("0 is falsy");
}

if ('0') {
    console.log("'0' is truthy");
} else {
    console.log("This won't run");
}
0 is falsy
'0' is truthy

Falsy vs Truthy Values

JavaScript has specific falsy values. Everything else is truthy:

// Falsy values
console.log(Boolean(0));         // false
console.log(Boolean(''));        // false
console.log(Boolean(null));      // false
console.log(Boolean(undefined)); // false
console.log(Boolean(false));     // false
console.log(Boolean(NaN));       // false

// Truthy values (including '0')
console.log(Boolean('0'));       // true
console.log(Boolean('false'));   // true
console.log(Boolean([]));        // true
false
false
false
false
false
false
true
true
true

Comparison

Expression Type Coercion? Result Reason
'0' == false Yes true Both convert to 0
if(0) No false 0 is inherently falsy
if('0') No true Non-empty strings are truthy

Best Practices

To avoid confusion, use strict equality and explicit conversions:

// Use strict equality (===) to avoid type coercion
console.log('0' === false);     // false
console.log('0' === 0);         // false

// Be explicit about conversions
console.log(Number('0') === 0); // true
console.log(Boolean('0'));      // true
false
false
true
true

Conclusion

The key difference is type coercion: == converts types before comparing, while if statements evaluate truthiness directly. Use === for predictable comparisons and understand JavaScript's falsy values to avoid confusion.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements