Course contentsShow
← JavaScript
Lesson 1941 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Optional Chaining with Function Calls

Call methods conditionally with obj.method?.() to prevent errors when the method doesn't exist.

Optional Chaining with Function Calls

You'll learn how to safely call methods that might not exist, preventing runtime errors when a function is undefined.

The Problem with Traditional Method Calls

When you try to call a method on an object, you're assuming that method exists. If it doesn't, JavaScript throws an error:

const user = {
  name: "Alice"
  // no greet method
};

user.greet(); // TypeError: user.greet is not a function

This crashes your code. Before optional chaining, you'd write verbose checks:

if (user.greet && typeof user.greet === 'function') {
  user.greet();
}

The Solution: ?.()

Optional chaining for function calls uses ?.() to call a method only if it exists. If the method is null or undefined, the expression returns undefined instead of throwing an error:

const user = {
  name: "Alice"
};

const result = user.greet?.(); // undefined, no error!

If the method exists, it gets called normally:

const admin = {
  name: "Bob",
  greet() {
    return `Hello, ${this.name}`;
  }
};

const greeting = admin.greet?.(); // "Hello, Bob"

Practical Use Cases

This is especially useful with callbacks or optional API methods:

const config = {
  onSuccess: () => console.log("Done!")
  // onError is missing
};

config.onSuccess?.(); // Logs "Done!"
config.onError?.();   // Does nothing, no crash

Think of it like a safety net: you attempt the call, but if the trapeze bar isn't there, you just fall softly into undefined rather than crashing to the ground.

Key Takeaway: Use obj.method?.() to call methods conditionally—if the method doesn't exist, you get undefined instead of a runtime error, making your code more resilient to missing or optional functionality.