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.
<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
filter_none
Output:
string true if part executed
Recommended Posts:
- Why “0” is equal to false in JavaScript ?
- When to use PreventDefault( ) vs Return false in JavaScript?
- How to check all values of an array are equal or not in JavaScript ?
- How to write :hover condition for a:before and a:after in CSS?
- Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript
- JavaScript Course | Understanding Code Structure in JavaScript
- JavaScript Course | Printing Hello World in JavaScript
- JavaScript Course | Logical Operators in JavaScript
- JavaScript Course | Conditional Operator in JavaScript
- JavaScript Course | Data Types in JavaScript
- JavaScript Course | JavaScript Prompt Example
- JavaScript Course | Operators in JavaScript
- JavaScript Course | Objects in JavaScript
- JavaScript Course | Functions in JavaScript
- JavaScript Course | Loops 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.



