Sub topic 1
Where JavaScript Expects a Boolean
Prerequisites
This chapter assumes you can declare variables with let and const, know JavaScript's primitive types and objects, write if statements and ternaries, call functions, and read console.log output.
Where JavaScript Expects a Boolean
Some places in the language need a yes-or-no answer. These are if and while conditions, the first operand of ? :, the operand of !, and the left operands of && and ||. When you put a value there, JavaScript converts it to a boolean using a fixed rule, called its truthiness. Your code does not need to produce true or false itself.
The Complete List of Falsy Values
A falsy value is one that converts to false. There are exactly eight:
const falsy = [false, 0, -0, 0n, "", null, undefined, NaN];
console.log(falsy.map(Boolean));
// [false, false, false, false, false, false, false, false]Everything Else Is Truthy, Including Some Surprises
Every value not on that list is truthy. That includes strings that look false and containers that are empty:
console.log(Boolean("0"), Boolean("false"), Boolean([]), Boolean({}));
// true true true trueConverting Explicitly with Boolean() and !!
Boolean(value) returns the value's truthiness. A single ! returns the opposite of it. Writing !! negates twice, which gives the same result as Boolean():
console.log(!!"hello"); // true
console.log(!!0); // false
console.log(!""); // trueUse either form when you need a real boolean, for example in a JSON payload or a typed API.
How || Picks the First Truthy Operand
|| does not return true or false. It reads its operands from left to right and returns the first truthy one. If none of them is truthy, it returns the last operand.
console.log("" || "fallback"); // "fallback"
console.log("a" || "fallback"); // "a"
console.log(null || 0); // 0Exercise
What does console.log([] || "empty", "0" || "zero", NaN || "") print?
Show answer
It prints [] "0" "". [] and "0" are truthy, so each is returned as is. NaN is falsy, so || returns its last operand, the empty string.