Menu

Optional Chaining and Nullish Coalescing in JavaScript
πŸ“°

Optional Chaining and Nullish Coalescing in JavaScript

DEV Community: frontendΒ·Arhan KhanΒ·about 18 hours ago
#JTBKelzT
#devtofrontend#devto#dev#user#const
Long article (343 words) β€” no AI summary yet.
Reading 0:00
15s threshold

Real data is messy. An API response is missing a field, a user object has no address, a settings object was never filled in. The old way to handle that was a ladder of && checks β€” ugly, repetitive, and easy to get wrong. Two modern operators fix this cleanly: optional chaining ( ?. ) and nullish coalescing ( ?? ).

Optional chaining stops the moment it meets null or undefined and returns undefined instead of throwing an error. No more crashes from reading a property of something that does not exist.

const user = { name : "Arhan" } ;

// Old way const city = user && user . address && user . address . city ;

// New way const city = user ? . address ? . city ; // undefined, no crash

Enter fullscreen mode

Exit fullscreen mode

It works for method calls and array access too. If the thing before ?. is missing, the whole expression short-circuits safely.

const result = user . getName ? . ( ) ; // only calls it if the method exists const first = users ? .…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.