DEV Community

Cover image for Optional Chaining (.?) in JS — Write Shorter & Safer Code!
shreya joshi
shreya joshi

Posted on

Optional Chaining (.?) in JS — Write Shorter & Safer Code!

Handling undefined or null checks in JavaScript used to mean a bunch of messy if statements or long && chains. But ES2020 introduced some game-changing operators — Optional Chaining (?.) — to help you write shorter ✏️, safer 🛡️, and more expressive code.

Optional chaining is a new operator in JavaScript that lets you safely access deeply nested properties or call functions — even if some parts of the path are null or undefined.

No more "Cannot read property of undefined" errors! 🎉

📜 Content

  1. ⚠️ The Problem
  2. 🤔 Optional Chaining - the Solution
  3. 🎮 Three Syntaxes
  4. 🔑Key Difference Before & After Optional Chaining
  5. 🧐 Reference
  6. 🎯 Wrapping Up

1. ⚠️ The Problem

Before optional chaining, you had to do this:

let theme;
if (user && user.profile && user.profile.settings) {
  theme = user.profile.settings.theme;
}
Enter fullscreen mode Exit fullscreen mode

Or worse, string together checks with &&:

const theme = user && user.profile && user.profile.settings && user.profile.settings.theme;
Enter fullscreen mode Exit fullscreen mode

That's verbose, ugly, and prone to mistakes!


2. 🤔 Optional Chaining - the Solution

Before optional chaining, we had to do a lot of manual checks like this:

❌ Without ?.: (Old way)

const user = null;

let city;
if (user && user.address && user.address.city) {
  city = user.address.city;
} else {
  city = undefined;
}
// This is verbose and error-prone! 
Enter fullscreen mode Exit fullscreen mode

Image description

✅ With ?.: (New way)

const user = null;
const city = user?.address?.city; // 🎯 city = undefined
Enter fullscreen mode Exit fullscreen mode

💡 What happens?
If user is null, JavaScript stops and returns undefined immediately — without throwing an error.
🎉 No extra if checks needed!


3. 🎮 Three Syntaxes

obj?.prop       // 🏷️ Access a property
obj?.[expr]     // 🎯 Access a dynamic property
func?.(args)    // 📞 Call a function if it exists
Enter fullscreen mode Exit fullscreen mode

Imagine we have this user object:

const user = {
  profile: {
    username: "coder123",
    settings: {
      theme: "dark" 🖤
    }
  },
  greet(name) {
    return `Hello, ${name}!`; 👋
  }
};
Enter fullscreen mode Exit fullscreen mode

1️⃣ Accessing Properties (obj?.prop)

Safely get a nested property:

// 🎯 Safe: returns "dark"
const theme = user?.profile?.settings?.theme;

// 😮‍💨 If user.profile is missing, returns undefined — no error
Enter fullscreen mode Exit fullscreen mode

2️⃣ Accessing Dynamic Properties (obj?.[expr])

Safely access a property by a dynamic key:

const key = "username"; 🔑
const username = user?.profile?.[key]; // 🎯 returns "coder123"

// 🚀 No errors even if profile is null or key is missing!
Enter fullscreen mode Exit fullscreen mode

3️⃣ Calling Functions (func?.(args))

Safely invoke a function if it exists:

// 📞 Safe function call
const greeting = user?.greet?.("Alice"); // 🎯 "Hello, Alice!"

// ❌ If greet is missing or undefined? -> No crash — returns undefined
Enter fullscreen mode Exit fullscreen mode

4. 🔑 Key Difference Before & After Optional Chaining

📜 Without ?. ✨ With ?.
Nested if or && checks One short expression
Verbose & error-prone Clean & safe
Throws errors if missing Returns undefined

5. 🧐 Reference

More on this topic in the official docs — check out:

👉 MDN Docs: Optional Chaining (?.)


🎯 Wrapping Up

That's all for today! 🎉

💜 Thanks for reading — I hope you learned something new!

If you have any questions, please reach out at: shreyajoshi.work@gmail.com


☕ Support My Work

If you found this post helpful, here's how you can support my work:

  • Follow me — I share daily web dev tips & insights.

Keep coding & happy learning! 🎉

Top comments (1)

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

This is extremely impressive, honestly i wish i had this years ago for all those gnarly nested checks i used to write you think there’s any catch to using optional chaining everywhere, or are there edge cases people still need to look out for