Sub topic 9
Truthy and Falsy Values
This chapter assumes you can read basic JavaScript, know the seven primitive types and how objects differ from them, and can run snippets in a browser console or Node.js. It covers ToBoolean, the simplest of the conversion operations. ToBoolean decides whether a value counts as "true" or "false" whenever JavaScript needs a yes-or-no answer.
The working model: a short list of falsy values
A value is falsy if ToBoolean converts it to false. A value is truthy if ToBoolean converts it to true. The specification does not compute this from the value's contents. It uses a fixed table keyed by type, and that table produces a short, closed list of falsy values:
| Type | Falsy values | Everything else |
|---|---|---|
| Boolean | `false` | `true` |
| Number | `0`, `-0`, `NaN` | truthy, including `Infinity` and negatives |
| BigInt | `0n` | truthy |
| String | `""` (length 0) | truthy, including `" "`, `"0"`, `"false"` |
| Undefined | `undefined` | (only one value) |
| Null | `null` | (only one value) |
| Symbol | none | every symbol is truthy |
| Object | none (one legacy exception below) | every object is truthy |
The rule to remember: memorize the eight falsy values, and treat everything else as truthy. The eight are false, 0, -0, 0n, "", null, undefined, and NaN.
const falsy = [false, 0, -0, 0n, "", null, undefined, NaN];
console.log(falsy.map(Boolean)); // all false
const surprisinglyTruthy = [
"0", "false", " ", [], {}, function () {},
new Boolean(false), new Number(0), new String(""),
Infinity, -1, Symbol("x")
];
console.log(surprisinglyTruthy.map(Boolean)); // all trueToBoolean never calls methods, never looks at an object's properties, and never throws. Objects skip ToPrimitive completely, so valueOf and toString play no part here. That makes ToBoolean the only conversion with no hooks you can customize.
Where ToBoolean runs
You rarely call ToBoolean yourself. The language applies it in these places:
- Conditions in
if,while,do...while, andfor - The test in a ternary:
cond ? a : b - The logical NOT operator
!, and so the double-NOT idiom!!value Boolean(value)called withoutnew- The left operand of
||and&&, to decide which operand to return. The operators return the operand itself, not a boolean. A later chapter covers this. - Callback results in array methods such as
filter,find,some, andevery
const value = "hello";
console.log(Boolean(value)); // true: the explicit form
console.log(!!value); // true: same result, terser
console.log(!value); // false
if (value) console.log("runs"); // implicit ToBoolean
console.log([0, 1, "", "a"].filter(Boolean)); // [1, "a"]Boolean(x) and !!x always give the same result. Choose Boolean(x) when you want readers to see the conversion. !!x is fine in codebases that already use it.
Common errors
Treating 0 or "" as "missing"
The most common truthiness bug is a check that is meant to test "was a value provided?" but also rejects valid falsy values.
function setVolume(level) {
if (!level) {
return "no level given";
}
return `volume set to ${level}`;
}
console.log(setVolume(5)); // "volume set to 5"
console.log(setVolume(0)); // "no level given": bug, 0 is a valid volume
console.log(setVolume(undefined)); // "no level given"
function setVolumeFixed(level) {
if (level === undefined || level === null) {
return "no level given";
}
return `volume set to ${level}`;
}
console.log(setVolumeFixed(0)); // "volume set to 0"The same trap catches filter(Boolean). It removes 0 and "" together with null and undefined, which may not be what you want for numeric or text data.
Expecting empty containers to be falsy
Arrays, objects, Maps, and Sets are truthy even when they are empty. To check for emptiness, test their size:
const items = [];
const settings = {};
const tags = new Set();
console.log(Boolean(items)); // true
console.log(items.length === 0); // true: the real emptiness check
console.log(Object.keys(settings).length === 0); // true
console.log(tags.size === 0); // truePython programmers hit this one often, because in Python empty lists and dicts are falsy.
Strings that look false
Data from URLs, forms, environment variables, localStorage, and CSV files arrives as strings. The strings "false", "0", and "null" are non-empty, so they are truthy.
const params = new URLSearchParams("debug=false&retries=0");
console.log(Boolean(params.get("debug"))); // true: "false" is a non-empty string
console.log(params.get("debug") === "true"); // false: compare the text instead
console.log(Number(params.get("retries"))); // 0: convert, then test
console.log(Boolean(params.get("missing"))); // false: get returns nullParse the string into the type you mean first, and test truthiness afterwards.
Wrapper objects are always truthy
new Boolean(false) creates an object, and every object is truthy. Calling Boolean without new returns a primitive, which is what you want.
const wrapped = new Boolean(false);
console.log(typeof wrapped); // "object"
console.log(wrapped ? "yes" : "no"); // "yes"
const plain = Boolean(false);
console.log(typeof plain); // "boolean"
console.log(plain ? "yes" : "no"); // "no"NaN slips through as "no value"
NaN is falsy, so if (!result) cannot tell a failed parse apart from a legitimate 0. When both can happen, check for each one directly with Number.isNaN(result) and result === 0.
Truthiness is not loose equality with true
Being truthy is a different thing from being == true. The == operator does not apply ToBoolean to its operands. When one side is a boolean, == converts that boolean to a number and then compares numbers.
console.log(Boolean("2")); // true: "2" is truthy
console.log("2" == true); // false: true becomes 1, "2" becomes 2
console.log(Boolean([])); // true: [] is truthy
console.log([] == false); // true: false becomes 0, [] becomes "" then 0The chapter on loose equality walks through the full algorithm.
The legacy exception: document.all
Browsers have one object that is falsy: document.all. It is an old API for collecting elements. The specification gives it a special internal slot called [[IsHTMLDDA]], so that typeof document.all is "undefined" and Boolean(document.all) is false. This keeps old feature-detection code like if (document.all) from running IE-only paths. You will not meet it in normal code, and it does not exist in Node.js. It is the only exception to "every object is truthy".
Exercise
Which of these values are falsy? "0", -0, [], 0n, " ", NaN, new Number(0), document.all (in a browser), Symbol("").
Show answer
-0, 0n, NaN, and document.all are falsy. "0" and " " are non-empty strings, [] and new Number(0) are objects, and every symbol is truthy, so all of those are truthy.
Exercise
A function showCount(n) begins with if (!n) return "loading"; and is called with the number of unread messages. What bug does this cause, and how should the check be written if undefined means "not loaded yet"?
Show answer
When there are zero unread messages, n is 0, which is falsy, so the function shows "loading" forever instead of 0. Write the check as if (n === undefined) return "loading";. If null can also mean "not loaded", use if (n == null) or if (n === undefined || n === null).
Exercise
Predict the output of console.log([] ? "A" : "B", [] == false ? "C" : "D"); and explain why the two halves seem to contradict each other.
Show answer
It prints A C. The ternary applies ToBoolean, and every object is truthy, so it picks "A". The == operator does not use ToBoolean. It converts false to 0 and [] to "" and then to 0, so 0 == 0 is true and it picks "C".