Optional Chaining and Nullish Coalescing in Modern JavaScript

Optional chaining (?.) and nullish coalescing (??), added in ES2020, eliminated an enormous amount of defensive if checks that used to litter JavaScript codebases.

const user = { profile: { name: 'Alice' } };

// Before: verbose, error-prone defensive checks
const city = user && user.profile && user.profile.address && user.profile.address.city;

// After: optional chaining short-circuits to undefined at any missing link
const cityModern = user?.profile?.address?.city; // undefined, no error thrown

// Works on function calls and array access too
user.greet?.();              // does nothing if greet doesn't exist, instead of throwing
const first = arr?.[0];

// Nullish coalescing: fallback ONLY for null/undefined, not other falsy values
const count = data.count ?? 0;   // 0 stays 0 if data.count is actually 0
const countOld = data.count || 0; // BUG: turns a real 0 into 0 anyway, but ALSO turns '' or false into 0 incorrectly

The critical difference from ||: ?? only falls back on null or undefined, not on other falsy values like 0, '', or false — fixing a genuine, common bug class where a legitimately falsy value was being incorrectly overridden by a default.