JavaScript1 min read
Stop Using && for Null Checks
Optional chaining (?.) is cleaner, safer, and more readable
S
Shahar Amir
Stop Using && for Null Checks
Still writing this?
javascript
1
const name = user && user.profile && user.profile.name;There's a better way.
Optional Chaining (?.)
javascript
1
const name = user?.profile?.name;Same result. Way cleaner.
How It Works
If any part is null or undefined, it short-circuits and returns undefined instead of throwing an error.
javascript
1234567
const user = null;
// ❌ Old way - crashesuser.profile.name; // TypeError!
// ✅ Optional chaining - safeuser?.profile?.name; // undefinedWorks With Methods Too
javascript
12345
// Call method only if it existsuser?.getFullName?.();
// Works with arraysusers?.[0]?.name;With Nullish Coalescing
Combine with ?? for default values:
javascript
1
const name = user?.profile?.name ?? "Anonymous";When to Use
- Accessing nested object properties
- Calling methods that might not exist
- Working with API responses
- Any data that might be incomplete
Stop the && chains. Use ?. — your future self will thank you.
#operators#es2020#clean-code
Stay Updated 📬
Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.