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 ? .β¦