We have all seen the dreaded "Cannot read property of undefined" error. Instead of writing long, defensive chains like if (user && user.profile && user.profile.name), start using the optional chaining operator (?.). It safely short-circuits the evaluation, returning undefined if any part of the chain is missing.
Pair this with the nullish coalescing operator (??) to provide a sensible default value. This combo makes your logic much more readable and prevents your application from crashing when an API response does not quite look the way you expected.
Top comments (0)