In a condition like if (value), JavaScript turns the value into true or false. Values that become false are falsy. Everything else is truthy.
The falsy values
There are only a handful:
| Value | Description |
|---|---|
false | the boolean |
0, -0, 0n | zero (number and BigInt) |
"" | the empty string |
null | no value |
undefined | not set |
NaN | not a number |
Everything else is truthy, including these surprises:
console.log(Boolean("0")); // → true (non-empty string)
console.log(Boolean("false")); // → true
console.log(Boolean([])); // → true (empty array)
console.log(Boolean({})); // → true (empty object)
console.log(Boolean(-1)); // → true
An empty array is truthy. To check for an empty array, test its length.
const items = [];
if (items) {
console.log("this runs, even though the array is empty");
}
if (items.length === 0) {
console.log("the array is empty"); // → the array is empty
}
Useful: checking for text
function greet(name) {
if (name) {
return `Hello, ${name}`;
}
return "Hello, stranger";
}
console.log(greet("Maya")); // → Hello, Maya
console.log(greet("")); // → Hello, stranger
console.log(greet()); // → Hello, stranger
The trap: zero
When 0 or "" is a valid value, a plain truthiness check is wrong.
function showCount(count) {
if (count) {
return `${count} items`;
}
return "No count";
}
console.log(showCount(0)); // → No count (probably not what you wanted)
Be explicit: if (count !== undefined), or use ??, see Nullish Coalescing.
Converting on purpose
Boolean(x) and !!x convert any value to a real boolean, as in Booleans.
When in doubt, be explicit
if (items.length > 0) is clearer than if (items.length), even though both work. Clear code beats short code.