Sub topic 6
Truthy and Falsy Values
This chapter assumes you already know JavaScript's primitive types, how to write if statements and functions, and the basic idea of type coercion from the earlier chapter. Here we look at one specific conversion, ToBoolean. It decides whether a value counts as "true enough" when JavaScript needs a yes-or-no answer.
What "truthy" and "falsy" mean
JavaScript accepts any value in places that expect a boolean, such as an if condition. It does not require a real true or false. It runs the abstract operation ToBoolean on the value instead. A value that ToBoolean turns into false is falsy. Every other value is truthy.
ToBoolean runs in these places:
- The conditions of
if,while,do...while, andfor - The first operand of the ternary operator
cond ? a : b - The operand of logical NOT
! - The left operand of
&&and||(covered in the next chapter) - An explicit call to
Boolean(value)
The complete list of falsy values
The falsy list is short and fixed, so you can memorize it. Any value not on it is truthy.
| Type | Falsy values |
|---|---|
| Boolean | `false` |
| Number | `0`, `-0`, `NaN` |
| BigInt | `0n` |
| String | `''` (the empty string) |
| Null | `null` |
| Undefined | `undefined` |
| Symbol | none: every symbol is truthy |
| Object | none: every object is truthy |
const falsy = [false, 0, -0, 0n, '', null, undefined, NaN];
console.log(falsy.map(Boolean)); // [false, false, false, false, false, false, false, false]
console.log(falsy.every((v) => !v)); // trueHow ToBoolean decides
ToBoolean is the simplest of the coercion operations. Unlike ToNumber and ToString, it never calls ToPrimitive. It does not run valueOf, toString, or Symbol.toPrimitive. It checks the value's type and, for a few types, its contents.
Because objects skip ToPrimitive, an object's contents never affect its truthiness. An empty array, an empty object, and even a wrapper around false are all truthy.
console.log(Boolean([])); // true
console.log(Boolean({})); // true
console.log(Boolean(new Boolean(false))); // true: it is an object
console.log(Boolean(new Number(0))); // true
console.log(Boolean(function () {})); // true
console.log(Boolean(Symbol())); // trueTruthy values that look falsy
Strings cause the most confusion. Only the empty string is falsy. Content is not inspected, so '0', 'false', and a single space are all truthy.
console.log(Boolean('0')); // true
console.log(Boolean('false')); // true
console.log(Boolean(' ')); // true: one space is not empty
console.log(Boolean(-1)); // true: any non-zero number
console.log(Boolean(Infinity)); // true
console.log(Boolean(0.1)); // trueThis matters for data from forms, URLs, environment variables, and localStorage, because those sources always give you strings. A setting stored as 'false' will pass an if check.
const raw = 'false'; // for example, read from process.env or localStorage
if (raw) {
console.log('This runs, even though the text says false');
}
const enabled = raw === 'true'; // compare the text explicitly
console.log(enabled); // falseTruthiness is not the same as `== true`
A common mistake is to assume that if (x) and if (x == true) mean the same thing. They do not. if (x) uses ToBoolean. x == true uses the loose equality algorithm, which first converts true to the number 1 and then compares numerically.
console.log(Boolean('2')); // true: non-empty string
console.log('2' == true); // false: true becomes 1, '2' becomes 2
console.log(Boolean([])); // true: every object is truthy
console.log([] == false); // true: [] becomes '' then 0, false becomes 0
if ([]) {
console.log('An empty array is truthy'); // this runs
}The [] case shows the two systems disagreeing. An empty array is truthy, and it is also loosely equal to false. Never compare against true or false with ==. Use the value directly in the condition, or compare it with === against the exact value you expect.
Converting explicitly: `Boolean()` and `!!`
You can get a real boolean in two equivalent ways:
const name = 'Ada';
console.log(Boolean(name)); // true
console.log(!!name); // true: the first ! negates, the second flips it back
console.log(!name); // falseBoth run ToBoolean. Boolean(x) is easier to read, and !!x is shorter. Do not write new Boolean(x). It creates a wrapper object, and that object is always truthy.
Boolean works as a callback because it is a function that returns a boolean. A common idiom removes every falsy entry from an array:
const mixed = [0, 1, '', 'a', null, NaN, 2, undefined];
console.log(mixed.filter(Boolean)); // [1, 'a', 2]The idiom is handy, but it also drops 0 and ''. Use it only when those values are really unwanted.
The classic bug: treating valid values as missing
Truthiness checks are a shortcut for "does this value exist?" The shortcut breaks when 0, '', or NaN is a legitimate value.
function setVolumeBuggy(level) {
if (!level) {
level = 50; // intended as a default for missing input
}
return level;
}
console.log(setVolumeBuggy(undefined)); // 50
console.log(setVolumeBuggy(0)); // 50: the user asked for mute and got 50
function setVolume(level) {
if (level === undefined || level === null) {
level = 50;
}
return level;
}
console.log(setVolume(0)); // 0
console.log(setVolume(undefined)); // 50The fix states what "missing" means instead of relying on falsiness. The ?? operator, covered later, expresses this check more briefly.
Arrays cause the opposite problem. An empty array is truthy, so if (items) cannot tell you whether the array has any elements. Check the length:
const items = [];
if (items) console.log('items exists'); // runs
if (items.length > 0) console.log('items has elements'); // does not runWhen to rely on truthiness
| Situation | Truthiness check is fine? | Better check |
|---|---|---|
| Value is an object or `null`/`undefined` | Yes | `if (user)` |
| Value may be `0` and `0` is valid | No | `x !== undefined`, `typeof x === 'number'` |
| Value may be `''` and `''` is valid | No | `x !== undefined && x !== null` |
| Checking whether an array is empty | No | `arr.length > 0` |
| String flag such as `'false'` | No | `x === 'true'` |
| Checking that a number is valid | No: `NaN` is falsy but so is `0` | `Number.isFinite(x)` |
The rule: use a truthiness check when every falsy value the variable could hold really means "absent". When it could hold a falsy value that counts as real data, write an explicit comparison.
Exercise
Without running the code, how many elements does this array contain after filtering, and which ones? [0, '0', [], '', ' ', null, new Boolean(false), NaN, -0, 0n, 'false'].filter(Boolean)
Show answer
Five elements: '0', [], ' ', new Boolean(false), and 'false'. Non-empty strings are truthy whatever they contain, and every object (including an empty array and a Boolean wrapper) is truthy. 0, '', null, NaN, -0, and 0n are falsy and get removed.
Exercise
A function reads a page number with function getPage(p) { return p || 1; }. Callers pass numbers starting at 0. Explain the bug and rewrite the function so that 0 is kept but undefined and null still become 1.
Show answer
The || operator uses ToBoolean on p, and 0 is falsy, so getPage(0) returns 1 instead of 0. A fix: function getPage(p) { if (p === undefined || p === null) { return 1; } return p; }. The later chapter's version is return p ?? 1;.
Exercise
Why does if ([]) {} run its body while [] == false is also true? Name the operation each one uses.
Show answer
The if statement uses ToBoolean, which never calls ToPrimitive and treats every object as truthy. The == operator uses the loose equality algorithm. It converts false to 0, then converts [] through ToPrimitive to '' and then to 0, so 0 == 0 is true. The two operations follow different rules.