Sub topic 1
Where JavaScript Expects a Boolean
Many JavaScript constructs need a yes-or-no answer before they can continue. An if statement must choose a branch. A while loop must decide whether to run again. JavaScript does not require that answer to be true or false. You can hand it a string, a number, an object, or undefined, and the engine converts that value to a boolean for you.
This chapter covers where that conversion happens, how the engine performs it, and which places look like boolean checks but behave differently. Later chapters build on this one. They cover the falsy values, the logical operators, and short-circuit evaluation.
Prerequisites
This chapter assumes you are comfortable with:
- Declaring variables with
letandconst - JavaScript primitive types (string, number, bigint, boolean, null, undefined, symbol) and objects
ifstatements and the ternary operatorcondition ? a : b- Writing and calling functions, including arrow functions
- Reading
console.logoutput in Node.js or a browser console
Boolean Contexts and the ToBoolean Operation
A boolean context is any position in the language where the engine needs a boolean but accepts any value. When a value lands in a boolean context, the engine runs an internal step that the ECMAScript specification calls ToBoolean. ToBoolean takes any value and returns true or false. It never throws.
A value that ToBoolean turns into true is called truthy. A value it turns into false is called falsy. Only a short, fixed list of values is falsy. The next chapter covers that list in full. For now, two facts are enough. The values 0, "", null, undefined, and NaN are falsy. Every object is truthy, including an empty array.
const values = [0, "", "text", [], null, 42];
for (const v of values) {
if (v) {
console.log(JSON.stringify(v), "-> if branch runs");
} else {
console.log(JSON.stringify(v), "-> else branch runs");
}
}
// 0 -> else branch runs
// "" -> else branch runs
// "text" -> if branch runs
// [] -> if branch runs
// null -> else branch runs
// 42 -> if branch runsThe if statement never compares v to true. It asks ToBoolean for a verdict and branches on that.
The Complete Set of Boolean Contexts
The table below lists every common place where ToBoolean runs.
| Construct | Value that gets converted | What the result controls | Column | Column |
|---|---|---|---|---|
| `if (x)` / `else if (x)` | `x` | Which branch runs | ||
| `while (x)` | `x`, before each iteration | Whether the loop body runs again | ||
| `do { } while (x)` | `x`, after each iteration | Whether the loop repeats | ||
| `for (init; x; step)` | `x`, before each iteration | Whether the loop body runs again | ||
| `x ? a : b` | `x` | Whether `a` or `b` is evaluated | ||
| `!x` | `x` | The negated boolean result | ||
| `x && y`, `x \ | \ | y` | `x` (and possibly `y`) | Which operand is returned |
| `arr.filter(fn)`, `find`, `findIndex`, `findLast`, `findLastIndex` | The callback's return value | Whether the element matches | ||
| `arr.some(fn)`, `arr.every(fn)` | The callback's return value | Whether the test passes for that element | ||
| `Boolean(x)` | `x` | The returned boolean |
The && and || row is different from the others. Those operators use ToBoolean to decide which operand to return, but they return the operand itself, not a boolean. Chapters on || and && cover this in detail.
Conditions in Loops
Loop conditions are converted on every iteration. This lets you write compact loops, and it also causes a classic bug:
const queue = ["a", "b", "c"];
let item;
while ((item = queue.shift())) {
console.log("processing", item);
}
// processing a
// processing b
// processing cqueue.shift() returns undefined once the array is empty. undefined is falsy, so the loop stops. Now change the data:
const jobs = [3, 0, 7];
let job;
while ((job = jobs.shift())) {
console.log("processing job", job);
}
console.log("left in queue:", jobs);
// processing job 3
// left in queue: [ 7 ]The value 0 is a real job ID, but it is falsy, so the loop ended early and job 7 never ran. When valid data can be falsy, test the condition you actually mean:
const jobs = [3, 0, 7];
while (jobs.length > 0) {
const job = jobs.shift();
console.log("processing job", job);
}
// processing job 3
// processing job 0
// processing job 7The Ternary Condition
The condition of ? : is a boolean context, exactly like if:
function describe(name) {
return name ? `Hello, ${name}` : "Hello, stranger";
}
console.log(describe("Ada")); // Hello, Ada
console.log(describe("")); // Hello, stranger
console.log(describe()); // Hello, strangerArray Callbacks
Array methods that test elements apply ToBoolean to whatever your callback returns. The callback does not have to return a real boolean.
const mixed = [0, 1, "", "hi", null, {}, NaN];
console.log(mixed.filter((x) => x)); // [ 1, 'hi', {} ]
console.log(mixed.filter(Boolean)); // [ 1, 'hi', {} ]
console.log([0, 5, 9].find((n) => n)); // 5
console.log([1, 2, 3].some((n) => n - 2)); // true (1 - 2 is -1, which is truthy)
console.log([2, 2].every((n) => n - 2)); // false (2 - 2 is 0, which is falsy)The some and every lines show how a callback can return a value you did not intend. The callback returns a number, and the method treats any non-zero result as a pass. If you meant to check n !== 2, write that comparison out.
How ToBoolean Works Internally
ToBoolean is a lookup on the value's type. It never calls any of your code.
| Type | ToBoolean result |
|---|---|
| Undefined, Null | `false` |
| Boolean | The value itself |
| Number | `false` for `+0`, `-0`, `NaN`; otherwise `true` |
| BigInt | `false` for `0n`; otherwise `true` |
| String | `false` for `""`; otherwise `true` |
| Symbol | `true` |
| Object | `true` (one legacy browser exception, covered in the final chapter) |
ToBoolean never calls valueOf or toString, which is why every object is truthy. That includes objects that would act like a falsy value in arithmetic or comparisons:
const sneaky = {
valueOf() {
console.log("valueOf called");
return 0;
},
};
if (sneaky) console.log("truthy; valueOf never ran");
// truthy; valueOf never ran
console.log(sneaky == 0);
// valueOf called
// true
const wrapped = new Boolean(false);
if (wrapped) console.log("a Boolean object is truthy");
// a Boolean object is truthyThe == comparison converts the object to a primitive, so valueOf runs. The if check does not. The new Boolean(false) case surprises people. It creates a wrapper object, and every object is truthy. Calling Boolean(false) without new returns the primitive false, which is what you almost always want.
Places That Look Boolean but Are Not
Some constructs feel like conditions, but they do not apply ToBoolean.
switch uses strict equality. It compares the discriminant to each case with ===, so no conversion happens:
const flag = 1;
switch (flag) {
case true:
console.log("matched true");
break;
default:
console.log("no match: 1 !== true");
}
// no match: 1 !== trueComparison with == uses different rules. x == true does not ask whether x is truthy. It converts both sides toward numbers:
console.log("hello" == true); // false ("hello" becomes NaN, true becomes 1)
if ("hello") console.log("but \"hello\" is truthy");
// but "hello" is truthyA later chapter explains these rules. For now, keep one rule in mind: to test truthiness, put the value directly in a boolean context. Do not compare it to true or false.
Optional chaining ?. and nullish coalescing ?? do not use ToBoolean. They check only for null or undefined. That difference is the reason ?? exists, and later chapters build on it.
Common Errors
- Treating a valid
0or""as missing. A condition likeif (count)orwhile ((x = next()))stops on legitimate zero or empty values. Usecount > 0,x !== undefined, or a length check. - Assuming an empty array or object is falsy.
if ([])andif ({})both run. Testarr.lengthorObject.keys(obj).lengthinstead. - Writing
if (x == true). This uses loose equality, not truthiness, and gives different answers for strings like"hello". - Returning arithmetic from test callbacks.
some((n) => n - 2)passes for every value except2, which is rarely the intent.
Exercise
Predict the output of this program, then explain why the third line differs from the first two. const box = new Boolean(false); console.log(box ? "yes" : "no"); console.log(!box); console.log(box == false);
Show answer
It prints "yes", then false, then true. The ternary condition and the ! operator both apply ToBoolean, which returns true for any object without calling valueOf, so box is truthy. The == comparison does not use ToBoolean. It converts the object to a primitive through valueOf, which gives false, and false == false is true.
Exercise
This function should return the first element of a list that is not null. Explain why it fails for [null, 0, 4] and rewrite the callback so it works. function firstPresent(list) { return list.find((x) => x); }
Show answer
find applies ToBoolean to the callback's return value. The callback returns x itself, and 0 is falsy, so find skips 0 and returns 4. To match "not null" (and usually "not undefined" as well), return an explicit comparison: list.find((x) => x !== null && x !== undefined), or list.find((x) => x != null). With that callback, firstPresent([null, 0, 4]) returns 0.
Exercise
Which of these positions apply ToBoolean to the value v: (a) if (v), (b) switch (v) { case true: }, (c) v ? 1 : 2, (d) [v].some((x) => x), (e) v ?? "default"?
Show answer
Positions (a), (c), and (d) apply ToBoolean. Position (b) compares v to true with strict equality. Position (e) checks only whether v is null or undefined.