Nullish Coalescing with ??
Provide fallbacks only for null and undefined, not all falsy values.
Nullish Coalescing with ?? is a free TypeScript Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The Nullish Coalescing Operator
The ?? operator returns its right-hand side only when the left-hand side is null or undefined. Otherwise it returns the left-hand value. It's the precise way to supply defaults.
const name: string | null = null;
const display = name ?? 'Guest';
console.log(display); // 'Guest'Only Nullish Triggers the Fallback
The key word is nullish: only null and undefined cause the right-hand side to be used. Every other value — including falsy ones — passes through unchanged.
console.log(0 ?? 99); // 0
console.log('' ?? 'x'); // ''
console.log(false ?? true); // false
console.log(null ?? 'def'); // 'def'The Problem With ||
The logical OR || uses the fallback for any falsy value: 0, '', false, NaN, as well as nullish. That often produces bugs when 0 or empty string are valid inputs.
const count = 0;
console.log(count || 10); // 10 — wrong! 0 is a valid count
console.log(count ?? 10); // 0 — correctDefaults Done Right
Use ?? when zero, empty string, or false are legitimate values you want to keep. Reserve || for cases where any falsy value truly should fall back.
function volume(v: number | undefined): number {
return v ?? 50; // 0 stays 0, undefined becomes 50
}
console.log(volume(0), volume(undefined));?? With Function Parameters
A common pattern is supplying a default for an optional parameter when undefined is passed, while preserving meaningful falsy inputs.
function greet(name?: string): string {
return 'Hello, ' + (name ?? 'friend');
}
console.log(greet('Ada'), greet());The Result Type of ??
The type of a ?? b removes null | undefined from a's type and unions with b's type. If a is string | null and b is string, the result is string.
const maybe: string | null = null;
const sure: string = maybe ?? 'default';
console.log(sure.toUpperCase());Chaining Defaults
You can chain ?? to try several sources in order, falling through to the next when a value is nullish. The first non-nullish value wins.
const fromEnv: string | undefined = undefined;
const fromConfig: string | null = null;
const value = fromEnv ?? fromConfig ?? 'hardcoded';
console.log(value);?? and Precedence
You can't mix ?? with || or && without parentheses — TypeScript requires them to avoid ambiguity. Always group explicitly.
const a: number | null = null;
const b = true;
// const x = a ?? 5 || 10; // Error without parens
const x = (a ?? 5) || 10;
console.log(x);Distinguishing Zero From Missing
A frequent real-world need: a temperature, score, or balance of 0 is valid data, while undefined means 'not provided.' ?? keeps these distinct; || conflates them.
function format(temp: number | undefined): string {
return (temp ?? 'N/A') + ' degrees';
}
console.log(format(0), format(undefined));?? With Object Properties
Reading an optional property and defaulting it is the everyday use of ??. It pairs naturally with optional chaining, which you'll combine next lesson.
type Opts = { retries?: number };
function run(o: Opts): number {
return o.retries ?? 3;
}
console.log(run({ retries: 0 }), run({}));When to Choose Which
Decision rule: if 0, '', or false are valid values you must preserve, use ??. If you genuinely want any falsy value replaced, use ||. Defaulting bugs almost always come from reaching for || by habit.
const username = '';
console.log(username || 'anon'); // 'anon' — empty replaced
console.log(username ?? 'anon'); // '' — empty keptQuick Check
Test your understanding of nullish coalescing.
Recap: Nullish Coalescing
You learned that ??:
- Returns the fallback only when the left side is
nullorundefined. - Preserves valid falsy values like
0,'', andfalse— unlike||. - Removes
null | undefinedfrom the result type. - Requires parentheses when mixed with
||or&&.
Next, we combine ?. and ?? together.
function port(v: number | undefined): number {
return v ?? 8080;
}
console.log(port(0), port(undefined));Frequently asked questions
Is the “Nullish Coalescing with ??” lesson free?
Yes — the full text of “Nullish Coalescing with ??” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Nullish Coalescing with ??”?
Provide fallbacks only for null and undefined, not all falsy values. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start TypeScript Academy?
No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Nullish Coalescing with ??” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this TypeScript Academy lesson?
Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Optional Chaining with ?.
- Nullish Coalescing with ??
- Combining ?. and ??
- Optional Calls and Element Access