Hiprup

What is optional chaining (?.) and nullish coalescing (??)?

Two ES2020 operators that make handling missing values cleaner.

  • Optional chaining (?.) — safely reads nested properties; if a link is null or undefined it returns undefined instead of throwing.

  • Nullish coalescing (??) — gives a fallback only when the left side is null or undefined, unlike || which also triggers on 0, "" or false.

Great together: read a deep value safely with ?. and supply a default with ?? in a single line.

const user = {
  name: 'John',
  address: {
    city: 'NYC'
  }
};

// Optional chaining
console.log(user?.address?.city);     // 'NYC'
console.log(user?.phone?.number);     // undefined (no error!)
console.log(user?.getEmail?.());      // undefined (safe method call)

// Without ?. — verbose null checks
// const city = user && user.address && user.address.city;
// With ?. — clean
const city = user?.address?.city;

// Nullish coalescing
const port = process.env.PORT ?? 3000;   // 3000 if PORT is null/undefined
const count = 0;
console.log(count || 10);  // 10 (wrong! 0 is falsy)
console.log(count ?? 10);  // 0  (correct! 0 is not null/undefined)

const name = '' ;           
console.log(name || 'default');  // 'default' (wrong! empty string is valid)
console.log(name ?? 'default'); // '' (correct!)

// Combined
const theme = user?.preferences?.theme ?? 'light';
const items = response?.data?.items ?? [];

// With arrays and methods
const first = arr?.[0];                // Safe array access
const result = obj?.method?.('arg');   // Safe method call

?. returns undefined if any part is null/undefined (no TypeError). ?? returns the right side only for null/undefined (not for 0, '', false). || treats ALL falsy values as 'missing' — ?? only treats null/undefined as 'missing'. Combined: safe deep access with proper fallback. ?. works with properties, arrays ([0]), and methods (method()).

?? vs || is the key comparison: ?? only triggers on null/undefined, || triggers on all falsy values (0, '', false). Show the 0 example (count ?? 10 = 0, count || 10 = 10).

Combined ?. + ?? is the modern null-safe pattern. These are ES2020 features.

What is optional chaining (?.) and nullish coalescing (??)? | Hiprup