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> // 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.
Recommended Posts:
- Why “0” is not equal to false in if condition in JavaScript ?
- When to use PreventDefault( ) vs Return false in JavaScript?
- false command in Linux with examples
- How to check all values of an array are equal or not in JavaScript ?
- Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript
- How to compare two JavaScript array objects using jQuery/JavaScript ?
- JavaScript Course | Understanding Code Structure in JavaScript
- JavaScript Course | Logical Operators in JavaScript
- JavaScript Course | Data Types in JavaScript
- JavaScript Course | Conditional Operator in JavaScript
- JavaScript Course | Printing Hello World in JavaScript
- JavaScript Course | Loops in JavaScript
- JavaScript Course | JavaScript Prompt Example
- JavaScript Course | Objects in JavaScript
- JavaScript Course | Functions in JavaScript
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.



