Home > Web Front-end > JS Tutorial > body text

Why Does '0' Equal False, But It's True When Tested with if in JavaScript?

Patricia Arquette
Release: 2024-11-04 19:19:02
Original
977 people have browsed it

Why Does

JavaScript Equality Puzzle: "0" Is False, But It's True When Tested with if

JavaScript's equality operators can lead to unexpected results, as demonstrated by the following code:

console.log("0" == false); // true
console.log(false == "0"); // true
Copy after login

This code implies that the string "0" is equivalent to the Boolean value false. However, the following code prints "ha" despite the condition being "0":

if ("0") console.log("ha"); // ha
Copy after login

Why is this happening?

To understand this behavior, we need to understand JavaScript's truthy and falsy values. In JavaScript, the following values are falsy:

false
0
""
null
undefined
NaN
Copy after login

All other values are truthy.

In the first two lines of the code snippet, the equality operator (==) performs type coercion to compare the string "0" with the Boolean value false. Since "0" is a falsy value, it is considered equal to false.

However, the if statement in the third line of code uses strict equality (===), which only considers values of the same type as equal. Since "0" is a string and false is a Boolean, the condition is evaluated as false.

To avoid confusion, it is recommended to use strict equality (===) when comparing values in JavaScript. The following modified code will print "nothing":

if ("0" === false) console.log("ha"); // nothing
Copy after login

By understanding the difference between equality (==) and strict equality (===), you can write JavaScript code that accurately compares values.

The above is the detailed content of Why Does '0' Equal False, But It's True When Tested with if in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template