Optional Chaining and Nullish Coalescing

Difficulty: Beginner

Question

Explain optional chaining (?.) and nullish coalescing (??) operators. How do they differ from && and ||?

Answer

Optional chaining (?.) safely accesses nested properties without throwing if an intermediate value is null or undefined - it short-circuits to undefined.

Nullish coalescing (??) returns the right-hand side only when the left-hand side is null or undefined (not when it is 0, false, or empty string).

Key differences: - obj?.prop vs obj && obj.prop: ?. is shorter and handles all nullish cases cleanly - a ?? b vs a || b: ?? only treats null/undefined as missing; || also treats 0, '', false as falsy

Code examples

Optional Chaining Patterns

const user = { name: 'Alice', address: { city: 'Mumbai' } };

const zip1 = user && user.address && user.address.zip;
console.log(zip1);

const zip2 = user?.address?.zip;
console.log(zip2);

console.log(user.getName?.());

const arr = null;
console.log(arr?.[0]);

const users = null;
const firstUser = users?.[0]?.profile?.name ?? 'Anonymous';
console.log(firstUser);

?. short-circuits the chain to undefined if any value is null or undefined, preventing TypeErrors.

Nullish Coalescing vs Logical OR

const config = { timeout: 0, retries: 3, enabled: false };

console.log(config.timeout || 5000);
console.log(config.enabled || true);

console.log(config.timeout ?? 5000);
console.log(config.enabled ?? true);
console.log(config.missing ?? 'default');

function getPort(options) {
  return options?.port ?? 3000;
}

console.log(getPort({ port: 0 }));
console.log(getPort({ port: 8080 }));
console.log(getPort(null));

?? is safer than || for default values when 0, false, or '' are valid - which is common with numeric and boolean config values.

Key points

Concepts covered

Optional Chaining, Nullish Coalescing, ?., ??, Short-circuit