Lesson 33: Mastering JavaScript Optional Chaining (?.) with challenges!

manoj ymkmanoj ymk
5 min read

Optional Chaining (?.) is a JavaScript syntax feature that allows you to safely access nested object properties without having to manually check for nullish (null or undefined) values at each level.

✅ Basic Example

let user = {};
console.log(user?.address?.street); // undefined, no error

Instead of crashing with Cannot read property 'street' of undefined, it gracefully returns undefined.

✅ Real-World Example

let element = document.querySelector('.profile');
let html = element?.innerHTML; // undefined if the element doesn't exist

This avoids runtime errors when querying DOM elements that may not be present.

Visual Flow:

user?.address?.street
   ↓        ↓
 undefined? stop here → return undefined

Optional chaining short-circuits evaluation as soon as it hits a null or undefined.


🔹 2. Fill Any Gaps

Let’s go deeper.

🧩 ?. Is Not an Operator

It’s syntax, not a standalone operator like + or &&. That means you can’t use it arbitrarily in expressions like:

let result = user?.address + ' street'; // ❌ Might be undefined + ' street'

🧩 Works With:

  • Property access: obj?.prop

  • Bracket notation: obj?.[key]

  • Function/method calls: obj.method?.()

  • Deletion: delete obj?.prop

🧩 Does NOT Work With:

  • Assignments:

      user?.name = "Alex"; // ❌ Syntax error
    
  • Declared references:

      console.log(nonDeclaredVar?.something); // ❌ ReferenceError
    

🔥 Short-Circuiting Quirk

let count = 0;
null?.doSomething(count++); // count not incremented!
console.log(count); // 0

⚠️ Common Mistakes

MistakeExplanation
Overusing ?.Hides bugs — e.g. if user should never be null, this masks it
Using on undeclared varsStill throws ReferenceError
Misusing with assignmentobj?.prop = value is invalid

🔹 3. Challenge Me Deeply

🟢 Basic

  1. Access a nested property safely using optional chaining.

  2. Use optional chaining to call a possibly undefined method.

  3. Use optional chaining with bracket notation and dynamic keys.

🟡 Intermediate

  1. Create a safe access utility function using optional chaining.

  2. Write a function that logs the .length of a possibly-null array using optional chaining.

  3. Safely delete a deeply nested property from an object using optional chaining.

🔴 Advanced

  1. Combine optional chaining with logical OR || to provide fallbacks.

  2. Use optional chaining inside a .map() call where objects might be incomplete.

  3. Refactor a deeply nested property access chain of 5+ levels using optional chaining.

  4. Safely call a method with optional chaining and pass arguments from another optional chain.

🎯 Brain-Twister

  1. What will the following return and why?
let obj = {
  method: () => null
};

console.log(obj.method?.().doesNotExist?.());

🔹 4. Interview-Ready Questions

❓ Concept Questions

  • What does optional chaining do internally?

  • What’s the difference between ?. and &&?

  • Why does user?.address.street still throw if user is not declared?

🧠 Scenario Questions

  • Given a JSON object from an API, how would you safely access a deeply nested optional property?

  • Refactor legacy code with multiple && checks using optional chaining.

🛠️ Debugging Questions

  • A dev uses user?.profile.name, but name is undefined even though profile exists. What’s wrong?

✅ Best Practices

✅ Do This❌ Avoid This
Use ?. when something is optional by logicBlindly chaining everything
Validate that the root variable is declaredUsing it without declaring first
Combine with default values (??, `

🔹 5. Real-World Usage

✅ Frontend

  • React Components: Conditionally access props or DOM elements.

  • Form Validation: form?.fields?.email?.value

  • API Integration: Access deeply nested data from APIs without checking every level.

const userName = apiResponse?.data?.user?.profile?.name ?? "Anonymous";

✅ Backend (Node.js)

  • Reading from optional config objects or environment-specific data.
const dbPort = config?.database?.port ?? 3306;

✅ Frameworks

  • Vue 3 Composition API: ref.value?.someProp

  • Next.js: Safe access to server-side props or headers


🔹 6. Remember Like a Pro

🧠 Mnemonic:

“If it might be empty, ask nicely with ?.

🧭 Mind Map

        Optional Chaining
              |
     -------------------------
    |            |            |
 obj?.prop   obj?.[key]   obj.method?.()
                          |
                     Stops if undefined/null

🧾 Cheatsheet

// ✅ Safe Read
obj?.prop;

// ✅ Safe Function Call
obj.method?.(args);

// ✅ Safe Bracket Notation
obj?.[key];

// ✅ Safe Delete
delete obj?.prop;

// ❌ Invalid Assignment
obj?.prop = value;

🔹 7. Apply It in a Fun Way

🎮 Mini Project: “Safe Config Viewer”

Build a simple UI that:

  1. Loads a nested config JSON (simulate API response).

  2. Uses ?. to safely access deep keys.

  3. Displays the path it took or returned undefined.

🛠 Steps:

  1. Create a mock config JSON with optional values.

  2. Build a form to input a path like theme?.colors?.primary.

  3. Parse and access it using eval or a custom resolver with ?..

  4. Output the result.

  5. Add fallback if undefined.

Extend It:

  • Let users input multiple paths and compare outputs.

  • Add an option to see what would happen without optional chaining.


🧠 Bonus Value Pack

🚀 Open-Source Projects That Use It:

⚠️ Dev Mistakes

  • Using ?. in expressions that rely on the result being not undefined (e.g. user?.profile.toUpperCase())

  • Confusing ?. with || or ??

🧩 Performance Tips

  • Optional chaining adds slight overhead — avoid in hot paths.

  • Don’t chain functions that aren’t memoized (e.g., getData()?.deepCall()?.another)

🧰 Polyfill

Use Babel's @babel/plugin-proposal-optional-chaining for older browsers.

0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk