JS CodeLab
modern javascriptbeginner

JavaScript Optional Chaining & Nullish Coalescing

•
Updated

Direct Answer & Overview

JavaScript optional chaining (?.) permits reading nested properties without manually checking each reference in the chain for null or undefined. Nullish coalescing (??) provides a fallback value only when a value is strictly null or undefined.

#optional-chaining#nullish-coalescing#es2020#modern-javascript

JavaScript Source Code

example.js
const user = {
  profile: {
    name: "Suresh"
  }
};

console.log(user.profile?.name);
// @ts-ignore
console.log(user.settings?.theme ?? "default");

How does this JavaScript code work?

Introduced in ECMAScript 2020, optional chaining (`?.`) short-circuits evaluation and evaluates to `undefined` if the preceding reference is nullish (`null` or `undefined`), avoiding runtime TypeError exceptions. Paired with the nullish coalescing operator (`??`), developers can supply clean default fallbacks only when a value is strictly nullish, preserving legitimate falsy values like `0`, `false`, and empty strings `""`.

What is the expected terminal output?

Executing this code in JS CodeLab produces the following stdout sequence in the developer console:

Console Standard Output
Suresh
default

Common mistakes to avoid

  • !Using the logical OR operator (||) instead of nullish coalescing (??), which erroneously overwrites valid falsy values like 0 or false.
  • !Overusing optional chaining on references that should be strictly guaranteed by application invariants, hiding upstream data bugs.
  • !Using ?. on root variables that are completely undeclared, which still throws a ReferenceError; optional chaining only guards properties.
  • !Attempting to use optional chaining on the left side of an assignment expression (e.g. obj?.prop = val is a SyntaxError).

Frequently Asked Questions

What is the difference between ?? (nullish coalescing) and || (logical OR)?

The ?? operator only falls back when the left operand is null or undefined. The || operator falls back on any falsy value, including 0, false, NaN, and empty strings ('').

Can optional chaining be used with function calls and array indices?

Yes. You can call optional functions with callback?.() and access optional array elements with array?.[index] safely.

Does optional chaining prevent ReferenceError on undeclared variables?

No. Optional chaining only protects property access on defined variables. Accessing an undeclared root variable still throws a ReferenceError.

Comprehensive Tutorial

Want an in-depth understanding of this topic?

Read our complete, interactive tutorial covering memory management, edge cases, and best practices.

Read the full objects tutorial →