Use Optional Chaining to Prevent Crashes

Optional chaining (?.) allows you to safely access nested object properties without throwing errors if any property in the chain is null or undefined. This eliminates the need for verbose null checks and prevents runtime crashes.

// ❌ Risky - throws error if user is undefined
const name = user.profile.name;

// ✅ Safe - returns undefined if any property is missing
const name = user?.profile?.name;

// Real example
const apiResponse = { data: { users: [{ name: "John" }] } };
const firstName = apiResponse?.data?.users?.[0]?.name; // 'John'

More on JavaScript

Recent Tips