Sub topic 2
The Complete List of Falsy Values
This chapter assumes you can declare variables with let and const, know JavaScript's primitive types and objects, write if statements and functions, and read console.log output. The previous chapter listed the places where JavaScript expects a boolean, such as if, while, the ternary operator and the logical operators. Here you learn exactly which values become false in those places.
JavaScript has no general idea of "empty". It has a short, fixed list of falsy values, defined by the language specification's ToBoolean operation. A value on that list converts to false in a boolean context. Every other value converts to true. If you memorize the list, you never have to guess.
The Eight Falsy Values
The list has eight entries. Each one belongs to a specific type.
| Value | Type | Where it usually comes from |
|---|---|---|
| `false` | boolean | Comparisons, flags, explicit literals |
| `0` | number | Counts, lengths, indexes, arithmetic results |
| `-0` | number | Rounding or multiplying negative numbers toward zero |
| `0n` | bigint | BigInt arithmetic that reaches zero |
| `""` | string | Empty input fields, `String.prototype.trim()` on whitespace |
| `null` | null | Deliberately "no value", APIs that return nothing found |
| `undefined` | undefined | Missing properties, unassigned variables, missing arguments |
| `NaN` | number | Failed numeric conversion, invalid math |
The quickest way to confirm the list is to run every entry through a real boolean context:
const falsy = [false, 0, -0, 0n, "", null, undefined, NaN];
for (const value of falsy) {
if (value) {
console.log("truthy:", value);
} else {
console.log("falsy:", value);
}
}
// falsy: false
// falsy: 0
// falsy: -0
// falsy: 0n
// falsy:
// falsy: null
// falsy: undefined
// falsy: NaNThe else branch runs for every entry. The if statement converted each value with the same rule that Boolean(value) uses. A later chapter covers Boolean() and !! in detail. This chapter uses Boolean as a callback in map because it shows the conversion compactly.
How the Engine Decides
ToBoolean does not inspect a value's contents in a general way. It looks at the type first and then applies one narrow test per type. Objects never get a content test at all.
This model explains most edge cases. The rest of this chapter goes through them type by type.
Numbers: Three Falsy Values
The number type contributes three falsy values: 0, -0 and NaN. Every other number is truthy. That includes negative numbers, tiny fractions and Infinity.
Zero Has Many Spellings
The source code can write zero in many ways. They all produce the same number value, so they are all falsy.
const zeros = [0, 0.0, +0, -0, 0x0, 0b0, 0o0, 0e5, 1 - 1, 0.1 * 0];
console.log(zeros.map(Boolean));
// [false, false, false, false, false, false, false, false, false, false]
const nonZeros = [1, -1, 0.0000001, Number.MIN_VALUE, Infinity, -Infinity];
console.log(nonZeros.map(Boolean));
// [true, true, true, true, true, true]Number.MIN_VALUE is about 5e-324, the smallest positive number JavaScript can represent. It is not zero, so it is truthy. Truthiness tests whether a value is exactly zero, not whether it is small.
Negative Zero
JavaScript numbers follow IEEE 754, which has a separate negative zero. It appears more often than you might expect:
const a = Math.round(-0.4);
const b = -1 * 0;
const c = 0 / -5;
console.log(a, b, c); // -0 -0 -0
console.log(Boolean(a)); // false
console.log(a === 0); // true
console.log(Object.is(a, 0)); // false
console.log(Object.is(a, -0)); // trueFor truthiness, -0 behaves exactly like 0. You only need to tell them apart in rare numeric code, and then Object.is is the tool to use.
NaN
NaN ("Not a Number") is the number type's value for an invalid numeric result. It is falsy, and it is easy to produce by accident:
const results = [0 / 0, Number("abc"), parseInt("px12", 10), Math.sqrt(-1), undefined + 1];
console.log(results); // [NaN, NaN, NaN, NaN, NaN]
console.log(results.map(Boolean)); // [false, false, false, false, false]
console.log(NaN === NaN); // false
console.log(Number.isNaN(results[0])); // trueBecause NaN is falsy, a check like if (price) treats a broken calculation the same as a price of zero. If your code needs to tell "zero" apart from "invalid", test with Number.isNaN explicitly. Never compare with === NaN, because NaN is not equal to anything, including itself.
BigInt: Only 0n
BigInt values follow the same rule as numbers without the extra cases. BigInt has no negative zero and no NaN, so 0n is the only falsy BigInt.
console.log(Boolean(0n)); // false
console.log(Boolean(-0n)); // false, because -0n is just 0n
console.log(Object.is(-0n, 0n)); // true
console.log(Boolean(1n)); // true
console.log(Boolean(5n - 5n)); // falseStrings: Only the Empty String
A string is falsy only when its length is 0. The quote style does not matter.
const strings = ["", '', ``, " ", "\n", "\t", "0", "false"];
console.log(strings.map(Boolean));
// [false, false, false, true, true, true, true, true]
console.log(" ".trim() === ""); // true
console.log(Boolean(" ".trim())); // falseA string that contains only whitespace is truthy, because spaces, tabs and newlines are characters. If a user types three spaces into a required form field, if (input) accepts it. Call .trim() first when whitespace should count as empty. The strings "0" and "false" are also truthy. The next chapter covers these surprises.
null and undefined: The Two "Nothing" Values
null and undefined are always falsy. Each is the only value of its own type, so there is no content test.
You meet undefined in several ways:
let notAssigned;
const obj = { a: 1 };
function noReturn() {}
function takesArg(x) { return x; }
console.log(notAssigned); // undefined
console.log(obj.missing); // undefined
console.log(noReturn()); // undefined
console.log(takesArg()); // undefined
console.log([1, 2][5]); // undefinednull usually means someone deliberately set "no value". For example, document.querySelector returns null when nothing matches, and String.prototype.match returns null when there is no match.
const match = "hello".match(/\d+/);
if (!match) {
console.log("no digits found"); // logs
}This is one of the most common good uses of a plain truthiness check. A successful match result is an array, which is always truthy, so the check cannot reject a real result by mistake.
false Itself
The boolean false is falsy because it converts to itself. The wrapper object new Boolean(false) is not on the list. It is an object, and every object is truthy:
const wrapped = new Boolean(false);
console.log(typeof wrapped); // "object"
console.log(Boolean(wrapped)); // trueAvoid new Boolean, new Number and new String in normal code. They create objects that defeat truthiness checks.
Common Errors with the Falsy List
The list is short, but it contains values that are often legitimate data. The typical bug is a truthiness check that rejects one of them.
| Check | Rejects by accident | Safer check when that value is valid |
|---|---|---|
| `if (count)` | `0` | `if (count !== undefined)` or `typeof count === "number"` |
| `if (index)` | `0` from `indexOf` or `findIndex` | `if (index !== -1)` |
| `if (name)` | `""` | `if (name !== undefined && name !== null)` |
| `if (total)` | `NaN` and `0`, without telling you which | `Number.isNaN(total)` and `total === 0` separately |
The following function shows how to separate the cases when the difference matters:
function describe(value) {
if (value === undefined || value === null) return "missing";
if (typeof value === "number" && Number.isNaN(value)) return "invalid number";
if (!value) return "falsy but present";
return "truthy";
}
console.log(describe(undefined)); // "missing"
console.log(describe(null)); // "missing"
console.log(describe(NaN)); // "invalid number"
console.log(describe(0)); // "falsy but present"
console.log(describe("")); // "falsy but present"
console.log(describe("hi")); // "truthy"Exercises
Exercise
Which of these values are falsy: -0, "0", 0n, " ", NaN, [], Number.MIN_VALUE, null?
Show answer
-0, 0n, NaN and null are falsy. "0" and " " are non-empty strings, [] is an object, and Number.MIN_VALUE is a positive non-zero number, so those four are truthy.
Exercise
The code const pos = text.indexOf("x"); if (pos) { console.log("found"); } fails to log "found" for text = "xyz". Explain why and fix it.
Show answer
indexOf returns 0 when the match is at the start of the string, and 0 is falsy, so the if body is skipped. It returns -1, which is truthy, when there is no match, so the check is also wrong for missing matches. Use if (pos !== -1) { console.log("found"); }.
Exercise
A form handler runs const qty = Number(input.value); if (!qty) { showError(); }. Which inputs trigger showError, and how would you report "not a number" separately from "zero"?
Show answer
showError runs for "0", for empty or whitespace-only input (Number("") and Number(" ") are 0), and for non-numeric input such as "abc", which gives NaN. To separate them, first check input.value.trim() === "" for empty input, then Number.isNaN(qty) for invalid input, then qty === 0 for zero.