Optional chaining: ‘?.’

let user = {}; // a user without "address" propertyalert(user.address.street); // Error!
let user = {};alert(user.address ? user.address.street ? user.address.street.name : null : null);
let user = {}; // user has no addressalert( user.address && user.address.street && user.address.street.name ); // undefined (no error)

Optional chaining

The optional chaining ?. stops the evaluation if the part before ?. is undefined or null and returns that part.

  • is the same as value.prop if value exists,
  • otherwise (when value is undefined/null) it returns undefined.
let user = {}; // user has no address

alert( user?.address?.street ); // undefined (no error)
// ReferenceError: user is not defined


The optional chaining ?. syntax has three forms:

  1. obj?.prop – returns obj.prop if obj exists, otherwise undefined.
  2. obj?.[prop] – returns obj[prop] if obj exists, otherwise undefined.
  3. obj.method?.() – calls obj.method() if obj.method exists, otherwise returns undefined.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.