4 min read
•Question 24 of 48easyWhat are Nullish Coalescing and Optional Chaining?
Safe handling of null/undefined.
What You'll Learn
- Optional chaining (?.)
- Nullish coalescing (??)
- Combining both
Optional Chaining (?.)
Safely access nested properties.
code.tsTypeScript
interface User {
name: string;
address?: {
city?: string;
zip?: string;
};
}
const user: User = { name: "John" };
// Without optional chaining
const city1 = user.address && user.address.city;
// With optional chaining
const city2 = user.address?.city; // undefined, no error
// Also works with methods and arrays
const length = user.name?.length;
const first = users?.[0];
const result = obj.method?.();Nullish Coalescing (??)
Default value for null/undefined only.
code.tsTypeScript
// ?? only triggers on null/undefined
const value1 = null ?? "default"; // "default"
const value2 = undefined ?? "default"; // "default"
const value3 = 0 ?? "default"; // 0
const value4 = "" ?? "default"; // ""
const value5 = false ?? "default"; // false
// Compare with ||
const value6 = 0 || "default"; // "default" (falsy!)Combining Both
code.tsTypeScript
const city = user.address?.city ?? "Unknown City";
const port = config.server?.port ?? 3000;