Frontend is a free bonus on CodeMentor AI β the main product is Python. Register to save your progress and unlock all 290 Frontend lessons + 1,000+ Python lessons.Sign up β free
TaskDefine const a = 0, const b = null, const c = ''. Log a ?? 'fallback' (expect 0), b ?? 'fallback' (expect 'fallback'), and c || 'fallback' (expect 'fallback').
Conditionals + the falsy gotcha
75 XP7 minFREE
Theory
The seven falsy values
In JavaScript, these all evaluate to false in an if:
false 0 0n (BigInt zero) "" (empty string) null undefined NaN
Everything else β including "0", "false", [], {}, -1 β is truthy. This is the source of half of all "weird JS" jokes.
Two operators worth knowing cold
const a = value ?? "default"; // "nullish coalescing" const b = value || "default"; // logical OR
?? returns value unless it's null or undefined. So:
0 ?? "default" // 0 (zero is a real value) 0 || "default" // "default" (zero is falsy)
?? saved a thousand bugs. Reach for it when you're providing a default and zero / empty string is meaningful.
Optional chaining
const city = user?.address?.city ?? "unknown";
If any link is null or undefined, the whole expression short-circuits to undefined (which ?? then catches). Replaces five lines of if (user && user.address) checks with one chain.
A real-world example
function welcome(user) {
const name = user?.name ?? "stranger";
return \`hi, ${name}\`;
}
welcome(); // "hi, stranger"
welcome({}); // "hi, stranger"
welcome({ name: "" }); // "hi, " β empty string is NOT nullish
welcome({ name: 0 }); // "hi, 0" β sameThe empty-string + zero cases bite β if you wanted to default those, use || instead of ??. Picking the right operator is a small decision that compounds across a codebase.
Live preview
console output appears hereβ¦