Module 5: Arrays, Objects, and Collections
Optional Chaining and Nullish Coalescing
Safely read optional nested properties and create sensible defaults.
Optional chaining (?.) stops a property access or call when the value immediately to its left is null or undefined. Instead of throwing, the expression evaluates to undefined.
const user = {
profile: { displayName: "Asha" },
};
console.log(user.profile?.displayName);
console.log(user.preferences?.theme); // undefined
Optional chaining can be used with property access, bracket access, and function calls. It should not replace validation when a missing value indicates invalid application state.
Nullish coalescing#
The ?? operator returns the right operand only when the left operand is null or undefined:
const configuredLimit = 0;
const limit = configuredLimit ?? 20; // 0
This is different from ||, which falls back for all falsy values such as 0, false, and an empty string.
Combine them carefully#
const displayName = user.profile?.displayName ?? "Guest";
Parentheses may be required when mixing nullish coalescing with && or ||; JavaScript forbids mixing them directly without grouping. Prefer simple expressions that are easy to inspect.
Practice#
Given a settings object where fontSize may be absent, write a safe expression that uses a default only when the value is nullish, while preserving a configured value of zero if that is valid for your application.