ShaharAmir
← Back to Blog
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 - crashes
user.profile.name; // TypeError!
// ✅ Optional chaining - safe
user?.profile?.name; // undefined

Works With Methods Too

javascript
12345
// Call method only if it exists
user?.getFullName?.();
// Works with arrays
users?.[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.