Use `??` when a fallback should replace only `null` or `undefined`. Unlike logical OR (`||`), it preserves other falsy values, including `0`, `false`, and the empty string. section 3.3.2
Keep a zero tax rate
In `primer/index.js`, `let taxRate;` makes `taxRate ?? 10` produce `10`. After `taxRate = 0`, the same expression produces `0`. Using `taxRate || 10` would produce `10` in both cases, incorrectly replacing the legitimate zero rate. section 3.3.2
The operator also supplies defaults for missing object properties: `hat.price ?? 0` handles an absent price, but assumes `hat` itself exists. Use `hat?.price ?? 0` when the object might also be `null` or `undefined`; optional chaining prevents the property read, and `??` supplies the fallback. section 3.5.1
Listing 11.32 Using a fallback value in the index.ts file in the src folder
interface Product {
name: string;
price: number;
}
class SportsProduct implements Product {
constructor(public name: string, public category: string,
public price: number) {
// no statements required
}
}
class ProductGroup {
constructor(...initialProducts: [string, Product][]) {
initialProducts.forEach(p => this[p[0]] = p[1]);
}
[propertyName: string]: Product;
}
let group = new ProductGroup(["shoes", new SportsProduct("Shoes",
"Running", 90.50)]);
group.hat = new SportsProduct("Hat", "Skiing", 20);
let total = group.hat.price + (group.boots?.price ?? 0);
console.log(`Total: ${total}`);
In `src/index.ts`, `(group.boots?.price ?? 0)` lets the total use zero when the indexed product is missing. Optional chaining protects the property access; nullish coalescing supplies the numeric fallback. section 11.5.1


