CKTIS / JavaScript
?.: optional access and calls
Optional chaining stops access when the checked base is null or undefined. It returns undefined instead of evaluating the remainder of that chain.
Version: ECMAScript 2020+
Syntax
object?.property
object?.[key]
callback?.()user?.name reads the property only when user is neither null nor undefined. user?.[key] supports a computed key, and callback?.() supports an optional call. Account for missing intermediate objects too, as in user?.address?.city.
The operator does not turn every error into undefined. An undeclared base name can still throw ReferenceError, and an existing but non-callable value in callback?.() throws TypeError. An exception raised inside the called function is not hidden either.
Short-circuiting applies to a continuous chain. If user is null, (user?.address).city can throw because the parentheses ended the optional chain. You cannot assign to user?.name: it is not a valid assignment target.
Combine optional access with ?? when appropriate, for example user?.name ?? "Guest". Use this for genuinely optional data and validate required fields explicitly; otherwise, malformed input structures can go unnoticed.
Examples
const user = null;
console.log(user?.address?.city ?? "Guest");
let index = 0;
console.log(user?.[index++]);
console.log(index);Result
Guest undefined 0
const callback = 7;
try {
callback?.();
} catch (error) {
console.log(error.name);
}Result
TypeError