JavaScript: Optional Chaining Operator

By Xah Lee. Date: . Last updated: .

New in JS2020.

Return the property value of object obj if it exist, but if obj is undefined or null or prop does not exist, return undefined.

This is useful when you have a long chain such as a.b.c.d , and some property may not exist. With the normal dot notation, it would error out.

console.log(undefined?.x === undefined);
console.log(null?.x === undefined);

// console.log(undefined.x);
// error: Uncaught TypeError: Cannot read property 'x' of undefined
const jj = {
  a1: 3,
  a3: { b1: 1, b3: 7 },

console.log(jj?.a2?.b3 === undefined);

JavaScript: Get Property

BUY Ξ£JS JavaScript in Depth