DEV Community

Toolloom
Toolloom

Posted on • Originally published at toolloom.com on

Saying Goodbye to Undefined Crashes

If you are tired of writing long logic chains like 'if (user && user.profile && user.profile.name)', it is time to embrace optional chaining. Using the '?.' syntax in JavaScript or TypeScript allows you to safely access deeply nested properties without worrying about a 'TypeError: Cannot read property of undefined' crashing your app.

To make it even more powerful, pair it with the nullish coalescing operator '??' to provide a default value. Writing 'const name = user?.profile?.name ?? "Guest";' is a clean, readable way to handle missing data while ensuring your UI always has something sensible to display.

Top comments (0)