Conditional control flow
Guard an if statement or loop with a value whose presence or state should control execution.
JS Puzzles · Const
JavaScript coerces values to booleans in conditions and other Boolean contexts. Only a small set of values is falsy; every other value is truthy.
JavaScript converts values to booleans whenever an operation requires a Boolean, including conditions and loops. The falsy values are false, 0, -0, 0n, "", null, undefined, NaN, and document.all; every other value is truthy. Boolean(value) or !!value performs the same conversion explicitly.
Boolean(value)A Boolean primitive when conversion is explicitly requested with Boolean(value) or !!value; Boolean contexts use the converted result for their operation.
const values = [false, 0, "", null, undefined, NaN, "0", [], {}];
for (const value of values) {
console.log(value, Boolean(value));
}Boolean(value) makes the implicit truthiness conversion explicit for each value.
Guard an if statement or loop with a value whose presence or state should control execution.
Normalize an arbitrary value into an actual Boolean for an API, stored state, or return value.
Use short-circuit expressions to select values based on their truthiness.
JavaScript applies Boolean coercion in Boolean contexts such as conditionals and loops. Values such as false, 0, an empty string, null, undefined, and NaN become false; other values become true.
Follow-up: How can coercion be made explicit? Use Boolean(value) or the double-NOT operator !!value; both produce a Boolean primitive.
The falsy set includes false, 0, -0, 0n, "", null, undefined, NaN, and document.all. Every other JavaScript value is truthy.
Follow-up: Is [] falsy because it is empty? No. Arrays and other objects are truthy, regardless of whether they contain elements.
Logical operators use truthiness but do not necessarily return a Boolean. For example, && returns the first falsy operand, or the last operand when all operands are truthy.
Follow-up: What does || return? It returns the first truthy operand, or the final operand if all operands are falsy.
truthyfalsyBoolean()Logical AND (&&)Logical OR (||)Logical NOT (!)