Hone

Lessons · JavaScript · ?? only catches null and undefined

A default only for missing

a ?? b gives b only when a is null or undefined. a || b gives b for every falsy a, including a real 0 or ''.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A limit of 0, a volume of 0, an empty string the user typed on purpose: || replaces them with the default and the bug is invisible. ?? was added to fix exactly that.

How to think about it

Use ?? for defaults. Use || only when you want every falsy value replaced. Never mix them in one expression without parentheses; the language refuses.

Worked example

console.log(0 ?? "fallback");
0: ?? only replaces null and undefined.
console.log(0 || "fallback");
fallback: || replaces every falsy value, including a real 0.
console.log(null ?? "fallback");
fallback.
console.log(undefined ?? 10);
10.

Your turn

A port with a default.

const port = config.port  3000;

The trap

a || b ?? c is a syntax error. Mixing || and ?? needs parentheses, on purpose, because their rules differ.

Next in JavaScript

Every JavaScript lesson on one page

Practise ?? only catches null and undefined on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.