Use Optional Chaining to Prevent Crashes

1 min read

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

Validate on Backend. Always.

Frontend validation improves user experience. It shows instant errors and prevents obvious mistakes like empty fields or invalid email formats. But frontend validation is never security. Anyone can bypass it using DevTools, Postman, or by directly calling your API. That’s why backend validation is mandatory it protects your database and business logic from invalid or malicious data.

Recent Tips

Validate on Backend. Always.

Frontend validation improves user experience. It shows instant errors and prevents obvious mistakes like empty fields or invalid email formats. But frontend validation is never security. Anyone can bypass it using DevTools, Postman, or by directly calling your API. That’s why backend validation is mandatory it protects your database and business logic from invalid or malicious data.

Use Optional Chaining to Prevent JavaScript Crashes | thehardik