JS: Optional Chaining Operator
(new in JS: ECMAScript 2020)
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.
💡 TIP: 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.const xx = { aa: 1 }; console.log(xx.aa?.bb === undefined); // true
console.log(undefined?.x === undefined); // true console.log(null?.x === undefined); // true