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
object?.property
object: the value that may benullorundefined.?.: optional chaining. Ifobjectisnullorundefined, it stops here and givesundefined.property: the property to read whenobjectexists.
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
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
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
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
node order.js
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
| Mistake | What happens | Do this instead |
|---|---|---|
Adding ?. to every property | A value that should always be there can go missing without an error, so the problem shows up later and somewhere else | Use ?. 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
- Optional chaining (?.) (opens in a new tab) (MDN)
- Run Node.js scripts from the command line (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments