liveBook · Manning

Nullish coalescing operator

As explained in Pro Angular 16

The nullish coalescing operator returns its right operand only when its left operand is null or undefined.

The nullish coalescing operator (`??`) supplies a fallback only when its left operand is `null` or `undefined`. Otherwise, it returns the left operand. Use it when a value such as `0` is valid and should not be replaced. section 3.4.7

Preserving zero

With `let price: number | undefined = 0`, `price || 100` produces `100` because `0` is falsy. `price ?? 100` produces `0`. If `price` is `undefined`, both expressions produce `100`. section 3.4.7

Listing 3.41. Using the nullish-coalescing operator in the main.ts file in the src folder
let val1: string | undefined;
let val2: string | undefined = "London";
let val3: number | undefined = 0;
 
let coalesced1 = val1 ?? "fallback value";
let coalesced2 = val2 ?? "fallback value";
let coalesced3 = val3 ?? 100;

console.log(`Result 1: ${coalesced1}`);
console.log(`Result 2: ${coalesced2}`);
console.log(`Result 3: ${coalesced3}`);

The complete TypeScript listing tests an undefined value, a string, and zero with `??`; its console results are a fallback, the string, and zero. section 3.4.7

Parenthesize a coalesced value before comparing it. The expression `price ?? 0 < 50` groups as `price ?? (0 < 50)`, not `(price ?? 0) < 50`. In a ternary expression choosing CSS classes, that mistake can select the same class regardless of the price. section 11.4.1

Choosing an Angular class

A class-binding expression such as `[class.bg-success]="(product.price ?? 0) < 50"` first substitutes zero for a missing price, then compares the result with 50. The parentheses make that order explicit. section 11.4.1

How Pro Angular 16 covers it

How deep it goes
Defines the operator through console examples and works through a comparison-precedence pitfall, without examining runtime internals.
Examples
Uses browser-console results for undefined, a string, and zero, then applies a missing-price fallback to CSS class selection.
What it assumes
Assumes basic JavaScript expressions and TypeScript declarations while explaining the difference between falsy and nullish fallbacks.
What you can do after
Practice/perform it by replacing truthiness-based fallbacks with `??` and parenthesizing coalesced values before comparisons.
How it connects
Contrasts with logical OR and connects to TypeScript union types, operator precedence, ternary expressions, and Angular class bindings.

Also explained in

Compare how 3 books explain nullish coalescing operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.