Why “0” is equal to false in JavaScript ?

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.

Example: This example illustrates why “0” equals to false.

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
      
    // JavaScript code to demonstrate 
    // why “0” is equal to false
      
    function GFG() {
      
        // Print type of "0"
        document.write(typeof "0" + "</br>");
      
        // Test whether "0" equals to false
        // or not. If "0" is equal to false
        // then "0" == false i.e.
        // false == false which return true
        var result = ("0" == false);
          
        // Print result
        document.write(result + "</br>");
          
        // Convert and print "0" to its numeric
        // value
        document.write(Number("0") + "</br>");
          
        // Convert and print false in numeric value
        document.write(Number(false) + "</br>");
          
        // So both numeric value are same
        // Therefore condition "0" == false
        // evaluates to true
        document.write("0" == false);
        document.write("</br>");
          
        // Or this statement
        document.write(Number("0") == Number(false));
    }
      
    // Driver code
    GFG();
      
</script>

chevron_right


Output:

string
true
0
0
true
true

So, from above it is clear that “0” is equal to false and reason behind this behavior is also clear, but when “0” is tested in if condition then it evaluates to true.



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.