JS: Optional Chaining Operator. x ?. y

By Xah Lee. Date: . Last updated: .

(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.d and 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 ?. key but in bracket notation.

const xx = {};

// access a property that does not exist.
// does not result in error.
console.assert(
 xx?.["aa"] === undefined,
);