Home > Article > Web Front-end > Six ways a Boolean value in JavaScript is false
Six situations in which Boolean values are false in JS
In JavaScript, Boolean has only two values, namely true and false. When we need to judge conditions, we need to use Boolean values.
However, in some cases, we need to determine whether a value is false, because we will only execute the corresponding code if it is false under certain specific conditions. Here are six situations in JS when a Boolean value is false, with specific code examples.
false
The most common situation when the Boolean value is false is to use the keyword false directly. When we set the value of a variable or expression to false, the Boolean value of the variable or expression is false.
let isFalse = false; if (isFalse) { console.log("这行代码不会执行"); }
0
The value 0 is treated as false in JS. Even negative numbers or decimal values that are 0 are treated as false.
let num = 0; if (num) { console.log("这行代码不会执行"); }
Empty string ("")
When a string does not contain any characters, it is an empty string, and its Boolean value is false.
let emptyStr = ""; if (emptyStr) { console.log("这行代码不会执行"); }
null
null means there is no value, it is a special object type. null is treated as false.
let nullValue = null; if (nullValue) { console.log("这行代码不会执行"); }
undefined
undefined is used to indicate that a variable has not been assigned a value, and its Boolean value is false.
let undefinedValue; if (undefinedValue) { console.log("这行代码不会执行"); }
NaN
NaN is the abbreviation of "Not a Number", which means it is not a valid number. The Boolean value of NaN is also false.
let nanValue = parseInt("abc"); if (nanValue) { console.log("这行代码不会执行"); }
Summary:
In JS, for the purpose of conditional judgment, we need to clearly know the six situations in which a Boolean value is false: false, 0, empty string ( ""), null, undefined, NaN. When we need to determine whether a value is false, we can use the code in the above example as a reference.
The above is the detailed content of Six ways a Boolean value in JavaScript is false. For more information, please follow other related articles on the PHP Chinese website!