Sub topic 1
What Counts as True: Truthy and Falsy Values
Prerequisites
This chapter assumes you know basic JavaScript syntax, can declare variables with let and const, and can write and call functions, including arrow functions. You should also be familiar with primitive types, arrays, and plain objects.
Truthy and Falsy Values
Any value can be used as a condition. JavaScript converts it to a boolean. Only a small fixed set of values is falsy: false, 0, -0, 0n, "", null, undefined, and NaN. Every other value is truthy, including empty arrays and objects.
console.log(Boolean(0), Boolean(""), Boolean(null), Boolean(NaN));
// false false false false
console.log(Boolean([]), Boolean({}), Boolean("0"), Boolean("false"));
// true true true trueStrict vs Loose Equality
=== compares type and value with no conversion. == converts its operands to a common type before it compares them, which gives surprising results.
console.log(0 == ""); // true
console.log(0 === ""); // false
console.log(null == undefined); // true
console.log(null === undefined); // falseUse === and !== by default. The one common use of == is x == null, which matches both null and undefined. The relational operators <, >, <=, and >= also convert types, and they compare two strings by character code, so "10" < "9" is true.
if, else if, and else
An if chain checks each condition in order and runs only the first branch whose condition is truthy.
function grade(score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else {
return "C or below";
}
}
console.log(grade(85)); // "B"Short-Circuiting with &&, ||, and ??
a && b returns a if a is falsy and b otherwise. a || b returns a if a is truthy and b otherwise. In both cases the right side runs only when it is needed. ?? falls back only when the left side is null or undefined, so it keeps valid values such as 0 and "".
const settings = { retries: 0, name: "" };
console.log(settings.retries || 3); // 3
console.log(settings.retries ?? 3); // 0
console.log(settings.name ?? "guest"); // ""
console.log(settings.timeout ?? 1000); // 1000Exercise
A user sets volume to 0. Why does const v = volume || 50; give the wrong result, and what should you write instead?
Show answer
0 is falsy, so || replaces it with 50. Write const v = volume ?? 50;, which falls back only when volume is null or undefined.
Exercise
What do [] == false and Boolean([]) return?
Show answer
[] == false is true, because both sides are converted to the number 0. Boolean([]) is true, because every object is truthy. This is one reason to prefer ===.