0Pricing
JavaScript Academy · Lesson

Optional Chaining with the ?. Operator

Safely access deeply nested properties.

The Problem

Reading a property on something that is undefined or null throws a TypeError. Optional chaining lets you read nested values safely.

const user = {};
console.log(user.profile && user.profile.name);

The ?. Operator

The optional chaining operator ?. stops and returns undefined if the value to its left is null or undefined, instead of throwing.

const user = {};
console.log(user.profile?.name); // undefined, no error

All lessons in this course

  1. Optional Chaining with the ?. Operator
  2. Nullish Coalescing with ??
  3. Combining ?. and ??
  4. Optional Calls and Index Access
← Back to JavaScript Academy