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.
<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> |
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.