Conditional checks
Run code only when a value is present or enabled.
JS Puzzles · Const
JavaScript converts values to Boolean in conditions and logical expressions. Most values are truthy; false, zero, the empty string, null, undefined, and NaN are falsy.
JavaScript converts an expression to a Boolean when it is used as a condition or with Boolean conversion. Falsy values include false, 0, -0, 0n, the empty string, null, undefined, and NaN; other values, including empty arrays and objects, are truthy.
Boolean(value)const values = [false, 0, "", null, undefined, NaN, [], {}];
for (const value of values) {
console.log(Boolean(value));
}
Boolean contexts convert values without changing the original value; objects and arrays are truthy, even when empty.
Run code only when a value is present or enabled.
Choose the first available value from several candidates.
Stop a computation when an earlier prerequisite is absent.
A truthy value is converted to true in a Boolean context, while a falsy value is converted to false. Falsy values include false, 0, -0, 0n, the empty string, null, undefined, and NaN.
Follow-up: What does Boolean([]) return? It returns true because arrays are objects, and objects are truthy.
The && operator evaluates from left to right and returns the first falsy operand. If every operand is truthy, it returns the last operand, preserving that operand's original value.
Follow-up: What does 0 && "fallback" return? It returns 0 and does not evaluate the right operand because 0 is falsy.
The || operator evaluates from left to right and returns the first truthy operand. If none is truthy, it returns the last operand, so it is commonly used to select a fallback.
Follow-up: Why can || be unsuitable for defaulting a valid zero? Because 0 is falsy; use ?? when only null or undefined should trigger the fallback.
Logical operatorsLogical NOT (!)if...elseBoolean