JS: Optional Chaining Operator
(new in 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 = {}; // access a property that does not exist. // does not result in error. console.assert(xx?.aa === undefined); const xx = { a: { b: 3 }, c: 2 }; // success console.assert(xx?.a?.b === 3); // property yy no exist, but do not generate error. console.assert(xx?.yy?.b === undefined); // test the behavior of Optional Chaining Operator console.assert(undefined?.x === undefined); console.assert(null?.x === undefined);