Sub topic 1
Where JavaScript Expects a Boolean
JavaScript lets you put any value where a boolean is expected. If the value is not already true or false, the engine converts it for that one check. This chapter covers where that conversion happens and how it works. Later chapters cover which values come out false.
Prerequisites
This chapter assumes you already know how to:
- Declare variables with
letandconst - Tell primitive types (string, number, boolean, null, undefined, bigint, symbol) apart from objects
- Write
ifstatements and use the ternary operator? : - Write and call functions, including arrow functions
- Read
console.logoutput in a browser console or Node.js
The Boolean Context
A boolean context is any place in the language where JavaScript needs a yes-or-no answer. When a value reaches one of these places, the engine applies an internal step the specification calls ToBoolean. ToBoolean maps every possible value to either true or false. It does not change the original value. It only decides which way the check goes.
A value that converts to true is called truthy. A value that converts to false is called falsy.
const values = ["hello", "", 42, 0, [], null];
for (const v of values) {
if (v) {
console.log(JSON.stringify(v), "-> if branch");
} else {
console.log(JSON.stringify(v), "-> else branch");
}
}
// "hello" -> if branch
// "" -> else branch
// 42 -> if branch
// 0 -> else branch
// [] -> if branch
// null -> else branchNo error is thrown, and none of these values is a boolean. The if statement converted each one to a boolean for its check.
Where the Conversion Happens
| Context | Example | What gets converted | Column | Column |
|---|---|---|---|---|
| `if` / `else if` | `if (user) {}` | The condition | ||
| `while`, `do...while` | `while (queue.length) {}` | The condition, on every loop | ||
| `for` loop test | `for (let i = 3; i; i--) {}` | The middle expression | ||
| Ternary | `name ? name : "guest"` | The part before `?` | ||
| Logical NOT | `!value` | The operand | ||
| `&&` and `\ | \ | ` | `a && b` | The left operand, to decide what happens next |
| Array callbacks | `arr.filter(x => x)` | The callback's return value in `filter`, `find`, `some`, `every`, `findIndex` |
The array methods catch people out because no if appears in your code. The method checks the callback's return value internally:
const mixed = [0, 1, "", "a", null, {}, undefined, -5];
console.log(mixed.filter(x => x)); // [1, "a", {}, -5]
console.log(mixed.some(x => x === 0)); // true
console.log(mixed.find(x => x)); // 1Places That Are Not Boolean Contexts
Some constructs look like they test a condition but do not use ToBoolean:
switchcompares with strict equality (===).switch (1) { case true: ... }does not match.==and===compare values by their own rules.x == trueis not the same asif (x), as a later chapter shows.- Plain assignment such as
const flag = "yes"stores the string, not a boolean.
switch (1) {
case true:
console.log("matched true");
break;
default:
console.log("no match"); // this runs
}Common Errors
- Assuming
if (arr)checks for an empty array. Every array converts totrue, empty or not. Checkarr.lengthinstead. - Returning a non-boolean from a
filtercallback without meaning to, for examplex => x.count, which drops every item whose count is0. - Expecting
switch (true)cases to match truthy values. They only match the literaltrue.
Exercise
What does this code log, and which line in it is a boolean context? const list = ["", "ok", 0, [], "0"]; console.log(list.filter(s => s).length);
Show answer
It logs 3. The return value of the filter callback is the boolean context. "" and 0 convert to false and are removed. "ok", [] and "0" convert to true and are kept.
Exercise
Will switch (5) { case true: console.log("A"); break; default: console.log("B"); } log "A" or "B"? Why?
Show answer
It logs "B". switch compares with strict equality, and 5 === true is false. The switch value is never converted to a boolean.