Skip to main content
0 reactions

How to Use Optional Chaining (?.) in JavaScript

Card titled Optional Chaining (?.), labelled JavaScript basics, with four ticked lines: failed.error?.message, the result Card declined, paid.error?.message, and the result undefined with no error.

Reading a property of null or undefined stops a JavaScript program with a TypeError. Optional chaining, written ?., checks the value first: if it’s null or undefined, the whole expression gives undefined and the program carries on.

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

SyntaxJavaScript
object?.property
  • object: the value that may be null or undefined.
  • ?.: optional chaining. If object is null or undefined, it stops here and gives undefined.
  • property: the property to read when object exists.

The same operator also works with brackets, object?.[name], and with function calls, func?.(). See Optional chaining (?.) (opens in a new tab) on MDN.

Prerequisites

The Example

Two orders in a file named order.js: a paid one, whose error is null, and a failed one, whose error holds a message.

Step 1: Write the Code

order.jsJavaScript
const paid = { id: 1, error: null };
const failed = { id: 2, error: { message: 'Card declined' } };

console.log(failed.error?.message);
console.log(paid.error?.message);
console.log(paid.error.message);

Step 2: Run It

TerminalBash
node order.js
Output (the lines that matter)Plain text
Card declined
undefined

TypeError: Cannot read properties of null (reading 'message')

failed.error?.message reads the message. paid.error?.message gives undefined, because paid.error is null. The last line has no ?., so reading message from null stops the program with a TypeError.

Common Mistakes

MistakeWhat happensDo this instead
Adding ?. to every propertyA value that should always be there can go missing without an error, so the problem shows up later and somewhere elseUse ?. only where the value may really be missing

FAQ

Can I get a default instead of undefined?

Yes, add ?? and the default: paid.error?.message ?? 'No error' gives No error.

What if the property itself is missing?

Then you get undefined too: for an empty object o, o.missing?.deeper gives undefined.

Conclusion

Put ?. after a value that may be null or undefined. You get undefined instead of a TypeError, and ?? turns that into a default.

Additional Resources

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments