The optional chaining (?.
) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined
or null
, the expression short circuits and evaluates to undefined
instead of throwing an error.
Syntax
obj.val?.prop
obj.val?.[prop]
obj.func?.(args)
Examples
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah',
},
};
console.log(adventurer.dog.name);
// TypeError: Cannot read properties of undefined
console.log(adventurer.dog?.name);
// undefined
console.log(adventurer.someNonExistentMethod?.());
// undefined
Tips
Variables before
?.
must be declared. The error occurs if the variable is not declared.console.log(user?.address); // ReferenceError: user is not defined
Don't abuse optional chaining. Optional chaining should only be used for objects that do not need to exist.
If the left operand is
null
orundefined
, the expression after?.
will not be evaluated. (Short-circuiting)let user = null; let x = 0; user?.sayHi(x++); // Nothing happens console.log(x); // 0
Optional chaining is not valid on the left-hand side of an assignment. But,
?.
can be used in combination withdelete
.delete user?.name; // Delete user.name if user exists user?.name = "Violet"; // SyntaxError: Invalid left-hand side in assignment // The error occurs because It is same with undefined = "Violet"