Ticker

6/recent/ticker-posts

🔗 Optional Chaining (?.) & Nullish Coalescing (??) — Write Safer JavaScript

🔗 Optional Chaining (?.) & Nullish Coalescing (??) — Write Safer JavaScript

These two operators quietly changed how we write JavaScript.

No more defensive && chains.
No more accidental fallbacks when values are valid.

Once you start using ?. and ??, your code becomes cleaner, safer, and easier to reason about.

🧠 Why These Operators Exist (Real Problems They Solve)

JavaScript apps deal with uncertain data all the time:

  • API responses
  • Nested objects
  • Optional configs

Before these operators, code was full of checks.

user && user.profile && user.profile.name;

It worked… but it wasn’t pleasant.

🔍 Optional Chaining (?.) — Safe Property Access

Optional chaining lets you safely access nested properties without crashing.

const name = user?.profile?.name;

If any part is null or undefined, JavaScript stops and returns undefined.

No errors. No noise.

📦 Optional Chaining With Functions & Arrays

It’s not just for objects.

Calling functions safely

user?.logout?.();

Accessing array elements

items?.[0];

This is incredibly useful with dynamic data.

🚫 What Optional Chaining Does NOT Catch

Optional chaining only handles:

  • null
  • undefined
user?.age // works
user?.age.toString() // ❌ if age is null

It stops early — it doesn’t validate data types.

❓ Nullish Coalescing (??) — Smarter Defaults

The ?? operator provides a default only when a value is null or undefined.

const username = input ?? "Guest";

This is different from ||.

⚖️ || vs ?? (This Matters a Lot)

0 || 10   // 10 ❌
0 ?? 10   // 0 ✅

Use ?? when:

  • 0, false, or "" are valid values

I’ve fixed real bugs caused by || accidentally overriding valid data.

🔁 Using Both Together (Very Common Pattern)

const city = user?.address?.city ?? "Unknown";

Safe access + smart fallback = clean logic.

This pattern shows up constantly in production code.

🚨 Common Mistakes Developers Actually Make

❌ Overusing optional chaining

If a value must exist, failing silently can hide bugs.

❌ Mixing || and ?? without parentheses

a || b ?? c // ❌ SyntaxError

Be explicit:

a || (b ?? c);

❌ Assuming ?. handles everything

It only protects against null and undefined.

🧪 Advanced Insight: When NOT to Use Them

Optional chaining is great for external data.
It’s risky for internal state where missing values indicate a bug.

Personally, I avoid ?. deep inside core business logic — I want errors to surface there.

🚀 Best Practice Summary

✅ Use ?. for uncertain or external data
✅ Use ?? for safe, intentional defaults
✅ Prefer ?? over || when falsy values are valid
✅ Avoid hiding real bugs with overuse
✅ Combine both for clean, readable logic

Reactions

Post a Comment

0 Comments