JS: Optional Chaining Operator. x ?. y
(new in ECMAScript 2020)
obj ?. key-
Return the value of property key of object obj, but if obj is undefined or null or key does not exist, return undefined.
π’ tip: This is useful when you have a long chain such as
a.b.c.dand some property may not exist. With the normal dot notation, result is an error.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, );
obj ?. [key]-
similar to
obj ?. keybut in bracket notation.const xx = {}; // access a property that does not exist. // does not result in error. console.assert( xx?.["aa"] === undefined, );