Sub topic 6
Calling Methods That Might Not Exist with ?.()
This chapter assumes you know how to call functions and methods, how this works in a method call, and how ?. guards property access from the previous chapters.
Sometimes a function is optional. A callback may not be passed, a plugin may skip a hook, or an object may only partly implement an interface. The ?.() form calls a function only when it exists, so you don't need an if check before every call.
The Basic Form
Put ?. between the function reference and its parentheses. If the reference is null or undefined, the call is skipped and the expression evaluates to undefined.
const logger = { info: (msg) => console.log(msg) };
logger.info?.("started"); // logs "started"
logger.debug?.("details"); // does nothing, returns undefined
const onDone = undefined;
onDone?.(); // does nothingThis replaces the older pattern:
const options = {};
if (typeof options.onProgress === "function") {
options.onProgress(50);
}
// Equivalent for the nullish case:
options.onProgress?.(50);
console.log("no error thrown");The two versions are not fully equivalent, which leads to the most common mistake.
It Checks for Nullish, Not for "Is a Function"
?.() asks only one question: is the value null or undefined? It does not check whether the value can be called. If the value exists but is a number, string, or plain object, JavaScript still tries the call and throws a TypeError.
const api = { version: "1.0" };
try {
api.version?.();
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // "api.version is not a function"
}Where You Put ?. Matters
A method call has two parts that might be missing: the object and the method. Each ?. guards only the value directly to its left.
| Expression | Guards | Throws when |
|---|---|---|
| `obj?.method()` | `obj` | `obj` exists but `method` is missing |
| `obj.method?.()` | `method` | `obj` is null or undefined |
| `obj?.method?.()` | both | the value exists but is not a function |
const plugin = null;
const partial = {};
console.log(plugin?.init?.()); // undefined
console.log(partial?.init?.()); // undefined
try {
partial?.init(); // partial exists, init does not
} catch (err) {
console.log(err.message); // "partial?.init is not a function"
}Guard only the links that can legitimately be missing. Writing ?. everywhere hides the cases where something that should exist doesn't.
`this` Is Preserved
When you write obj.method?.(), the method still receives obj as this, the same as a normal method call. You don't lose the binding the way you would by first copying the method into a variable.
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
},
};
console.log(counter.increment?.()); // 1
console.log(counter.increment?.()); // 2Arguments Are Not Evaluated When Skipped
If the call is skipped, JavaScript never evaluates its arguments. Expensive work or side effects inside the argument list don't run. A later chapter covers short-circuiting in full.
let calls = 0;
const build = () => { calls++; return "report"; };
const hooks = {};
hooks.onReport?.(build());
console.log(calls); // 0A Practical Pattern: Optional Callbacks
function fetchData(onSuccess, onError) {
const ok = Math.random() > 0.5;
if (ok) {
onSuccess?.({ items: [1, 2, 3] });
} else {
onError?.(new Error("Request failed"));
}
}
fetchData((data) => console.log("Got", data.items.length, "items"));
fetchData(); // safe: no callbacks providedThe caller can pass either callback, both, or neither. The function only invokes the ones it actually received.
Exercise
Given const config = { onLoad: "init" };, what happens when you run config.onLoad?.(), and why?
Show answer
It throws a TypeError ("config.onLoad is not a function"). ?.() only skips the call when the value is null or undefined. The string "init" is not nullish, so JavaScript tries to call it and fails.
Exercise
With const widget = undefined;, which of these throws: widget.render?.(), widget?.render(), or widget?.render?.()?
Show answer
Only widget.render?.() throws, because .render is read from undefined before the call guard is reached. widget?.render() short-circuits at widget?., so the whole chain, including the call, is skipped. widget?.render?.() short-circuits the same way. Both return undefined.