Optional Chaining & Nullish Coalescing

Published by Brayan K

Optional chaining (?.) safely reads deeply nested values without crashing on missing data, and nullish coalescing (??) supplies a fallback only when a value is null or undefined.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Preserve a real value while supplying a missing one

A default has a meaning: use it when the data is absent, or use it when the current value is unusable. Those are different decisions. Optional chaining and nullish coalescing implement the first kind of decision for null and undefined; they do not decide whether an application should accept zero, an empty string or a particular object.

const preferences = { volume: 0, hints: false, caption: "" };
// Nullish defaults preserve values the user deliberately chose.
console.log(preferences.volume ?? 50);
console.log(preferences.hints ?? true);
console.log(JSON.stringify(preferences.caption ?? "Caption"));
// A genuinely missing property receives its fallback.
console.log(preferences.theme ?? "light");

// ✅ Expected output:
// 0
// false
// ""
// light
for (const value of [0, false, "", null, undefined, NaN]) {
  console.log(JSON.stringify([String(value), value || "fallback", value ?? "fallback"]));
}

// ✅ Expected output:
// ["0","fallback",0]
// ["false","fallback",false]
// ["","fallback",""]
// ["null","fallback","fallback"]
// ["undefined","fallback","fallback"]
// ["NaN","fallback",null]

Use logical OR when the contract really says “replace any falsy value.” Use nullish coalescing when only null or undefined means missing. NaN is not nullish, so a numeric default does not validate it. The last row displays null because JSON.stringify serializes NaN that way; the coalescing result is still NaN. Type Coercion (== vs ===) owns truthiness and coercion; this lesson owns the short-circuit boundaries of these operators.

Guard the part of a property chain that can be absent

const first = null;
const second = { profile: null };
const third = { profile: { name: "Mina" } };
console.log(first?.profile?.name);
console.log(second?.profile?.name);
console.log(third?.profile?.name);

// ✅ Expected output:
// undefined
// undefined
// Mina

The operator checks the value immediately before it. If that value is nullish, the continuous optional chain stops and yields undefined. If it is present, normal property access continues, including normal getters and their possible exceptions. Do not add a guard to hide a field your program actually requires; a missing required field should be diagnosed at its validation boundary.

const data = { profile: null };
console.log(data?.profile.name);

// ✅ Expected error:
// TypeError: Cannot read properties of null (reading 'name')
const data = null;
console.log((data?.profile).name);

// ✅ Expected error:
// TypeError: Cannot read properties of undefined (reading 'name')

The grouped expression first produces undefined, then ordinary .name access runs on that result. Keep the optional chain continuous when its remaining operations should be skipped together. Parentheses are not inherently unsafe; they change where one expression ends and another begins.

Skipped access also skips its key or argument computation

let lookups = 0;
const absent = null;
console.log(absent?.[lookups++], lookups);
const present = ["first"];
console.log(present?.[lookups++], lookups);

// ✅ Expected output:
// undefined 0
// first 1
let calls = 0;
function fallback() { calls++; return "default"; }
console.log(0 ?? fallback(), calls);
console.log(null ?? fallback(), calls);
console.log(false ?? fallback(), calls);

// ✅ Expected output:
// 0 0
// default 1
// false 1

This is short-circuit evaluation, not a promise that getters or helper functions are pure. Keep side effects deliberate. The fallback is evaluated when the left value is nullish; constructing an expensive fallback before the expression removes that benefit. Pure Functions, Immutability & Side Effects owns side-effect discipline.

const source = {
  get title() { throw new Error("title getter failed"); }
};
console.log(source?.title);

// ✅ Expected error:
// Error: title getter failed

Optional calling checks absence, not callability

const counter = {
  value: 3,
  read() { return this.value; }
};
console.log(counter.read?.());
console.log(counter.missing?.());

// ✅ Expected output:
// 3
// undefined
const service = { save: 7 };
service.save?.();

// ✅ Expected error:
// TypeError: service.save is not a function

Use object?.method?.() when the object and method may each be absent by contract. If a present property could be a nonfunction, validate typeof before calling it or reject the shape. Optional calling does not catch an exception thrown by the called function. The this Keyword owns receiver binding.

console.log(missingOptionalRoot?.value);

// ✅ Expected error:
// ReferenceError: missingOptionalRoot is not defined

A declared variable whose value is undefined can be guarded. An undeclared identifier still fails name resolution. Use a deliberate environment check such as typeof window when an API may not exist at all; do not assume window?.document makes an undeclared window safe in every runtime.

Choose assignment and grouping deliberately

const settings = { count: 0, name: null };
settings.count ??= 10;
settings.name ??= "Guest";
console.log(settings.count, settings.name);
let gets = 0, sets = 0;
const slot = {
  get value() { gets++; return 0; },
  set value(next) { sets++; }
};
slot.value ??= 5;
console.log(gets, sets);

// ✅ Expected output:
// 0 Guest
// 1 0

Nullish assignment mutates its target when a fallback is needed. It is not a copying operation. A getter is still evaluated, and a setter is used only if assignment is required. A constant binding or a frozen property can still reject a required write. Do not use it when the application promises immutable input.

const enabled = false, fallback = true;
console.log((enabled ?? fallback) || "disabled");
console.log(enabled ?? (fallback || "disabled"));

// ✅ Expected output:
// disabled
// false

JavaScript does not allow an unparenthesized mixture of ?? with || or &&. Choose parentheses according to the intended decision, not just to silence the parser. Optional chaining is also not a general assignment target: assigning through object?.field is invalid syntax. Use an explicit presence check before a write.

try { new Function("target", "target?.field = 1"); }
catch (error) { console.log(error.name); }

// ✅ Expected output:
// SyntaxError
const absent = null;
const present = { draft: true };
console.log(delete absent?.draft);
console.log(delete present?.draft, Object.hasOwn(present, "draft"));

// ✅ Expected output:
// true
// true false

The true result of delete on an absent optional base does not prove a property existed. Distinguish a missing property from an explicit undefined value with the object’s own-property contract when that difference matters. Object Methods (keys, entries, assign, freeze) owns property ownership.

Guided exercise: default only what is missing

Fill the literal hints. Preserve the empty label and disabled hint flag, while supplying the missing page size. This exercise illustrates selection only; the brief also validates the selected values.

const input = { ui: { hints: false }, user: { label: "" } };
const hints = input.ui?.hints ___ true; // 👉 replace ___ with ??
const pageSize = input.ui?.pageSize ___ 20; // 👉 replace ___ with ??
const label = input.___?.label ?? "Guest"; // 👉 replace ___ with user
console.log(hints, pageSize, JSON.stringify(label));

// ✅ Expected output:
// false 20 ""

Brief: selection is followed by validation

Implement readDisplayOptions for ordinary decoded JSON data. The root, ui and user may each be nullish; any present container must be a non-array object. Select theme, pageSize and showHints from ui, and label from user. Nullish defaults are light, 20, true and Guest respectively. Preserve false and an explicit empty label.

Accept only light/dark themes, integer page sizes from 1 through 100, boolean hint flags, and string labels of at most 40 UTF-16 code units after trimming. A preserved zero page size must therefore fail validation; it must not silently become 20. Ignore extra fields by returning a new selected record. Do not mutate input, interpret getters/proxies, store preferences or authorize a user.

function readDisplayOptions(input) {
  const isRecord = value => value !== null && typeof value === "object" && !Array.isArray(value);
  if (input != null && !isRecord(input)) throw new TypeError("options must be an object or nullish");
  if (input?.ui != null && !isRecord(input.ui)) throw new TypeError("ui must be an object or nullish");
  if (input?.user != null && !isRecord(input.user)) throw new TypeError("user must be an object or nullish");
  const theme = input?.ui?.theme ?? "light";
  const pageSize = input?.ui?.pageSize ?? 20;
  const showHints = input?.ui?.showHints ?? true;
  const rawLabel = input?.user?.label ?? "Guest";
  if (theme !== "light" && theme !== "dark") throw new TypeError("invalid theme");
  if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 100) throw new TypeError("invalid page size");
  if (typeof showHints !== "boolean") throw new TypeError("invalid hint flag");
  if (typeof rawLabel !== "string" || rawLabel.trim().length > 40) throw new TypeError("invalid label");
  return { theme, pageSize, showHints, label: rawLabel.trim() };
}
console.log(JSON.stringify(readDisplayOptions(null)));
console.log(JSON.stringify(readDisplayOptions({ ui: { theme: "dark", showHints: false }, user: { label: "" } })));
for (const input of [{ ui: { pageSize: 0 } }, { ui: 3 }, { user: { label: 9 } }]) {
  try { readDisplayOptions(input); }
  catch (error) { console.log(error.name, error.message); }
}
const source = { ui: { pageSize: 5 }, user: { label: " Mina " } };
const before = JSON.stringify(source), result = readDisplayOptions(source);
console.log(result.label, JSON.stringify(source) === before, result === source);

// ✅ Expected output:
// {"theme":"light","pageSize":20,"showHints":true,"label":"Guest"}
// {"theme":"dark","pageSize":20,"showHints":false,"label":""}
// TypeError invalid page size
// TypeError ui must be an object or nullish
// TypeError invalid label
// Mina true false

The operators choose a candidate value. Validation establishes whether that candidate meets this application’s contract. Deep Dive into JSON, Parsing & Serialization owns decoding and schema boundaries, while Intro to TypeScript & Strong Typing Concepts explains what a static checker can infer after these runtime checks.

Practice quiz

What does this complete program print? const x={n:0};console.log(x?.n??9);

  • 0
  • 9
  • undefined
  • null

Answer: 0. Zero is present and non-nullish.

What does this complete program print? const x=null;let i=0;console.log(x?.[i++],i);

  • undefined 1
  • undefined 0
  • null 0
  • null 1

Answer: undefined 0. A nullish base skips the computed key expression.

What does this complete program print? const x={flag:false};console.log(x.flag||true,x.flag??true);

  • false false
  • false true
  • true false
  • true true

Answer: true false. OR replaces false; nullish coalescing preserves it.

What does this complete program print? const x={read:3};try{x.read?.()}catch(e){console.log(e.name)}

  • undefined
  • 3
  • ReferenceError
  • TypeError

Answer: TypeError. A present nonfunction is still not callable.

What does this complete program print? const x=null;try{console.log((x?.a).b)}catch(e){console.log(e.name)}

  • TypeError
  • undefined
  • null
  • ReferenceError

Answer: TypeError. Grouping ends the optional chain before ordinary property access.

What does this complete program print? const x={n:0};x.n??=5;console.log(x.n);

  • 5
  • 0
  • undefined
  • null

Answer: 0. Nullish assignment does not write over zero.

What does this complete program print? let calls=0;const f=()=>++calls;console.log(false??f(),calls);

  • true 1
  • false 1
  • false 0
  • 1 1

Answer: false 0. The fallback is skipped for false.

What does this complete program print? const x={label:""};console.log(JSON.stringify(x.label??"Guest"));

  • "Guest"
  • undefined
  • null
  • ""

Answer: "". An explicitly empty string survives a nullish default.

Continue this course

Related lessons