Skip to content
Related Articles
Open in App
Not now

Related Articles

Why “0” is not equal to false in if condition in JavaScript ?

Improve Article
Save Article
  • Last Updated : 19 Jan, 2023
Improve Article
Save Article

The reason behind this behavior is that JavaScript treats non-empty string as true. First, “0” is converted into its boolean value, by automatic type conversion which is true. Therefore, if statement executes. 

Example: This example illustrates why “0” is not equal to false in if() condition

javascript




// JavaScript script to demonstrate 
// why “0” is not equal to false in 
// ‘if’ condition 
  
function GFG() { 
  
    // Print type of "0" 
    condole.log(typeof "0" ); 
  
    // Print boolean value of "0" 
    condole.log(Boolean("0") ); 
  
    // Boolean value of "0" is true so 
    // 'if' part will execute 
    if("0") { 
        condole.log("if part executed"); 
    
    else
        condole.log("else part executed"); 
    
  
// Driver code 
GFG();

Output:

string
true
if part executed
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!