In JavaScript, values are often evaluated in Boolean contexts such as if statements, logical expressions, and loops. Rather than requiring strict true or false, JavaScript converts values into truthy or falsy.
Definition
Truthy values evaluate to true.
Falsy values evaluate to false.
JavaScript defines a limited set of falsy values; every other value is truthy.
Falsy Values.
The following values always evaluate to false:
false
0, -0
0n
"" (empty string)
null
undefined
NaN
Boolean(false); // false
Boolean(0); // false
Boolean(""); // false
Boolean(null); // false
Example in an if statement:
let value = "";
if (value) {
console.log("runs");
} else {
console.log("does not run");
}
Truthy Values
Truthy values include:
Non-zero numbers
Non-empty strings
Arrays, objects, and functions
Boolean(1); // true
Boolean("hello"); // true
Boolean([]); // true
Boolean({}); // true
if ("hello") {
console.log("This runs because non-empty strings are truthy");
}
Logical Operators in Practice
OR (||) returns the first truthy value:
"" || "default"; // "default"
AND (&&) returns the first falsy value or the last value:
"ok" && "done"; // "done"
0 && "no"; // 0
Common Pitfalls and Best Practices
"0" is truthy because it’s a non-empty string
NaN is falsy, but typeof NaN === "number"
Use Number.isNaN() to check for NaN
Use explicit checks when exact behavior matters:
value === ""
value == null (checks both null and undefined)
Top comments (0)