Skip to main content
The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. It functions similarly to the standard property accessor (.), but if the operand on the left-hand side evaluates to a nullish value (null or undefined), the expression short-circuits and evaluates to undefined rather than throwing a TypeError.

Syntax Variations

The operator supports three distinct syntactic forms for different evaluation contexts:

Evaluation Mechanics

When the JavaScript engine encounters the ?. operator, it performs a strict nullish check on the left-hand operand.
  1. If the left operand is null or undefined: The engine immediately halts further evaluation of the current chain (short-circuiting) and returns undefined.
  2. If the left operand is any other value (including falsy values like 0, "", or false): The engine proceeds with the property access or function invocation.

Mechanical Equivalence and Single Evaluation

Conceptually, optional chaining acts like a ternary operation, but with a critical distinction: the left-hand side is evaluated exactly once. If the left operand is a function call or a getter, a standard ternary check would evaluate it twice, whereas ?. guarantees single evaluation. The true mechanical equivalent relies on an implicit temporary variable:

Short-Circuiting Behavior

Short-circuiting applies only to the specific chain where the operator is used. If the left operand is nullish, the right-hand side of the ?. is never evaluated. This is critical when the right-hand side contains expressions with side effects.

Technical Constraints and Nuances

  • Undeclared Root Variables: The ?. operator only protects against nullish values, not undeclared references. The root variable of an optional chain must be declared in the current scope, otherwise the engine throws a ReferenceError.
undeclaredVar?.prop; // ReferenceError: undeclaredVar is not defined
  • Constructor Invocation: Optional chaining cannot be used in conjunction with the new operator.
new obj?.(); // SyntaxError: Invalid optional chain from new expression
  • Grouping Precedence: Parentheses interrupt the short-circuiting chain. If an optional chain is wrapped in parentheses, the resulting undefined will be passed to subsequent operations outside the parentheses, which may result in a TypeError.
const obj = null; obj?.a.b; // Evaluates to undefined (short-circuits the whole chain) (obj?.a).b; // Throws TypeError: Cannot read properties of undefined (reading ‘b’)