brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: JavaScript ?. stops a chain at null or undefined instead of throwing

Javascript
~/tips/tip-javascript-optional-chaining-operator

obj?.prop

Reads a property or calls a function only when the value in front of it exists.

The error “Cannot read properties of undefined” has been in my life for too long. Optional chaining is the short fix, and it has worked in all browsers since July 2020.

There are three forms:

obj?.prop
obj?.[expr]
func?.(args)

If the part before ?. is null or undefined, the whole expression gives undefined and nothing to the right is evaluated. No exception.

const customerCity = customer.details?.address?.city;
onError?.(err.message);

The second line calls onError only if it exists. It pairs well with ?? for a default:

const city = customer?.city ?? "Unknown city";

Short-circuiting covers one continuous chain. Wrap part of it in parentheses and it stops working: (a?.b).c still throws a TypeError when a is null.

Caveats from MDN. You cannot assign to an optional chain: object?.property = 1 is a SyntaxError. ?.() only guards against a missing method. If the property exists but is not a function, it still throws, and when the object itself can be missing you need obj?.method?.(). The root variable must be declared, because ?. won’t save you from a ReferenceError. And be careful that it hides typos: a misspelled property name returns undefined quietly.

Further reading: MDN: Optional chaining

More Javascript tips node --inspect-brk app.js const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null shareButton.addEventListener("click", async () => { All Javascript tips (40) All topics

Link