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.
<script>
function GFG() {
document.write( typeof "0" + "</br>" );
var result = ( "0" == false );
document.write(result + "</br>" );
document.write(Number( "0" ) + "</br>" );
document.write(Number( false ) + "</br>" );
document.write( "0" == false );
document.write( "</br>" );
document.write(Number( "0" ) == Number( false ));
}
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.
Last Updated :
27 Jun, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...