JavaScript Optional Chaining

Access nested properties safely with optional chaining and pair it with nullish coalescing for defaults.

TL;DR

  1. 01Access nested properties safely using the ?. operator.
  2. 02Provide fallback values for missing properties using the ?? operator.
  3. 03Short-circuit evaluation chains immediately when any intermediate value is nullish.

Tips

  1. 01Combine the ?. and ?? operators to read nested properties and supply fallback values in one statement.
  2. 02Utilize optional chaining with ?.() when invoking callback methods that might not exist on target objects.

Warnings

  1. 01Remember that optional chaining only guards against null and undefined rather than other falsy values.
  2. 02Avoid overusing the ?. operator because it can hide actual bugs by silently swallowing unexpected errors.

Optional Chaining Basics

    ?.

    Accesses nested properties safely without throwing errors if the parent object is nullish.

    const user = { profile: null };
    const email = user.profile?.email; // undefined
    Plain dot access

    Throws a TypeError if you attempt to read properties of a missing parent.

    const user = { profile: null };
    // Throws: Cannot read properties of null
    const email = user.profile.email;
    Multi-level chaining

    Chains multiple optional checks together to guard against several missing layers.

    const data = {};
    const city = data.user?.address?.city; // undefined
    Mixed chaining

    Combines optional chaining with standard dot access once existence is verified.

    const user = {
      profile: { settings: { theme: "dark" } }
    };
    const theme = user.profile?.settings.theme; // safe

Method and Array Access

    ?.()

    Invokes an object method conditionally only if it is defined and executable.

    const obj = {};
    obj.greet?.(); // does nothing, no error
    Optional callbacks

    Invokes optional callback parameters in a function safely to prevent errors.

    function handleClick(onClick) {
      onClick?.(); // calls only if provided
    }
    ?.[index]

    Accesses array elements or computed keys safely when the parent list is nullish.

    const arr = null;
    const item = arr?.[0]; // undefined
    Dynamic objects

    Combines optional brackets and dot identifiers when walking variable data shapes.

    const res = data?.items?.[0]?.name;

Nullish Coalescing

    ??

    Returns the right-hand value only when the left-hand expression is nullish.

    const name = user.name ?? "Anonymous";
    ?? versus ||

    Preserves falsy values like zero or empty strings, unlike standard logical OR.

    const count = 0;
    console.log(count ?? 10); // 0
    console.log(count || 10); // 10
    Safeguard chain

    Combines optional chaining and nullish fallback to supply safe defaults.

    const theme = user.settings?.theme ?? "light";
    ??=

    Assigns a default value to a variable only if it is currently nullish.

    let config = {};
    config.timeout ??= 3000;
    console.log(config.timeout); // 3000

Short-Circuiting

    Evaluation halt

    Stops expression evaluation immediately when a nullish value is encountered.

    let called = false;
    const getEmail = () => { called = true; };
    const user = null;
    user?.getEmail();
    console.log(called); // false
    Expressions value

    Resolves the entire chained expression to undefined when short-circuited.

    const val = null?.a?.b;
    console.log(val); // undefined
    Independent checks

    Short-circuits exclusively at optional chain points rather than plain dots.

    const obj = { a: null };
    // Throws TypeError: Cannot read property c of null
    const val = obj.a?.b.c;

In Practice

FAQ