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

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

string
true
if part executed


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.