JS: Optional Chaining Operator

By Xah Lee. Date: .

New in JS2020.

obj?.prop
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); // true
console.log(null?.x === undefined); // true

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

console.log(obj?.a2?.b3 === undefined); // true
βˆ‘ JS in Depth
XAH
Buy Xah JavaScript Tutorial
βˆ‘ JS in Depth
XAH

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Regular Expression

Date

Set Object

Map Object

Number

Misc