Sub topic 6
Calling Methods That Might Not Exist with ?.()
Some functions are optional by design. A component may accept an onClose callback that callers can leave out. A plugin may implement some lifecycle hooks and skip others. A newer runtime may provide an API that an older one lacks. The optional call form, ?.(), lets you call such a function only when it is present, without wrapping every call in an if statement.
This chapter assumes you already know how to call functions and methods, how this works inside a method called as obj.method(), and how plain ?. property access returns undefined when its left side is null or undefined.
The Basic Form
The syntax puts ?. between the function expression and the parentheses that hold its arguments:
const logger = { info: (msg) => console.log(msg) };
logger.info?.("started"); // logs "started"
logger.debug?.("details"); // does nothing, returns undefined
const onDone = undefined;
onDone?.(); // does nothingThe rule is the same one plain ?. uses. JavaScript evaluates the expression to the left of ?.. If the value is null or undefined, the call is skipped and the whole expression evaluates to undefined. Otherwise the function is called normally with the given arguments.
You will see three shapes in real code:
| Form | Meaning |
|---|---|
| `fn?.(x)` | Call the variable `fn` if it is not nullish |
| `obj.method?.(x)` | Call `obj.method` if that property is not nullish |
| `obj?.method?.(x)` | Skip if `obj` is nullish, then skip if `obj.method` is nullish |
The placement of ?. decides which value is being checked. The check always applies to whatever sits immediately to its left.
Where the Question Mark Goes
Programmers often put ?. in the wrong spot. Compare these three calls against objects that are missing different parts:
const withMethod = { greet: () => "hi" };
const withoutMethod = {};
const noObject = null;
// Checks only the method
console.log(withMethod.greet?.()); // "hi"
console.log(withoutMethod.greet?.()); // undefined
try {
noObject.greet?.();
} catch (e) {
console.log(e.constructor.name, "-", e.message);
// TypeError - Cannot read properties of null (reading 'greet')
}
// Checks only the object
console.log(noObject?.greet()); // undefined
try {
withoutMethod?.greet();
} catch (e) {
console.log(e.constructor.name, "-", e.message);
// TypeError - withoutMethod?.greet is not a function
}
// Checks both
console.log(noObject?.greet?.()); // undefined
console.log(withoutMethod?.greet?.()); // undefinedobj.method?.() protects you when the method may be missing but the object is guaranteed to exist. obj?.method() protects you when the object may be missing but, if it exists, the method is guaranteed to be there. Use obj?.method?.() only when both can really be absent. Adding ?. at every step "just in case" hides information about what your code actually expects. A later chapter on best practices covers that cost.
The following diagram shows how JavaScript evaluates obj.method?.(args).
It Checks for Nullish, Not for "Is a Function"
The optional call does not test whether the value is a function. It tests only whether the value is null or undefined. Any other value goes on to an ordinary call, and calling a non-function throws:
const config = { onSave: "yes please" };
try {
config.onSave?.();
} catch (e) {
console.log(e.message); // config.onSave is not a function
}
const counter = { tick: 0 };
try {
counter.tick?.();
} catch (e) {
console.log(e.message); // counter.tick is not a function
}This behavior is deliberate. If a property that should hold a function holds a string, something is wrong, and a loud error is more useful than a silent skip. It does mean ?.() is the wrong tool when the value comes from an untrusted or loosely typed source, such as parsed JSON, user configuration, or a third-party object whose shape you do not control. In those cases, check the type explicitly:
function runHook(hooks, name, ...args) {
const hook = hooks?.[name];
if (typeof hook === "function") {
return hook(...args);
}
return undefined;
}
console.log(runHook({ init: () => "ready" }, "init")); // "ready"
console.log(runHook({ init: "not a function" }, "init")); // undefined
console.log(runHook(null, "init")); // undefinedHow It Differs from `fn && fn()`
Before optional chaining, a common idiom was callback && callback(). The two forms disagree on falsy non-function values:
const values = [undefined, null, 0, "", false];
for (const cb of values) {
const viaAnd = cb && cb();
let viaOptional;
try {
viaOptional = cb?.();
} catch (e) {
viaOptional = "TypeError";
}
console.log(String(cb).padEnd(9), "&&:", viaAnd, "| ?.():", viaOptional);
}
// undefined &&: undefined | ?.(): undefined
// null &&: null | ?.(): undefined
// 0 &&: 0 | ?.(): TypeError
// &&: | ?.(): TypeError
// false &&: false | ?.(): TypeErrorThe output shows two differences. && returns the falsy value itself (null, 0, "", false), while ?.() always returns undefined when it skips. And && silently skips the call for 0, "", and false, while ?.() reaches the call and throws. A common use of && is something like isEnabled && handler(), where the left side is a boolean flag rather than the function itself. That pattern has no ?.() equivalent and should stay as it is.
`this` Is Preserved
When you write obj.method?.(), the method runs with this bound to obj, exactly as obj.method() would. Optional chaining does not detach the method from its object:
const account = {
owner: "Ada",
describe() {
return `Account of ${this.owner}`;
},
};
console.log(account.describe?.()); // "Account of Ada"
// Copying the method into a variable loses `this`, with or without ?.
const detached = account.describe;
try {
console.log(detached?.());
} catch (e) {
console.log(e.constructor.name); // TypeError (this is undefined in strict code)
}The last call only throws if the code runs in strict mode, which is the default inside ES modules and classes. In a sloppy-mode script, this falls back to the global object and the call returns "Account of undefined". In either case the cause is the ordinary JavaScript rule about detached methods. Optional chaining neither causes the problem nor fixes it.
Arguments Are Not Evaluated When the Call Is Skipped
If the function is nullish, JavaScript does not evaluate the argument list at all. Any side effects or expensive work in the arguments never happen:
let built = 0;
function buildReport() {
built++;
return { rows: 1000 };
}
const exporter = {};
exporter.send?.(buildReport());
console.log(built); // 0 (buildReport was never called)This is usually what you want, because there is no point building data for a function that will not run. It can surprise you if an argument does work you rely on elsewhere, such as incrementing a counter or logging. Keep required side effects out of the argument list of an optional call. The chapter on short-circuiting covers exactly how far this skipping reaches through a longer chain.
Common Use Cases
Optional callbacks in an options object
function downloadFile(url, { onProgress, onComplete } = {}) {
for (let pct = 0; pct <= 100; pct += 50) {
onProgress?.(pct);
}
onComplete?.(url);
}
downloadFile("/a.zip", {
onProgress: (p) => console.log(`progress ${p}%`),
});
// progress 0%
// progress 50%
// progress 100%
// (onComplete was not provided, so nothing else happens)Plugin lifecycle hooks
const plugins = [
{ name: "auth", setup: () => console.log("auth ready") },
{ name: "metrics" }, // no setup hook
];
for (const plugin of plugins) {
plugin.setup?.();
}
// auth readyFeature detection
Some APIs exist only in certain runtimes or versions. An optional call runs the API where it exists and skips it elsewhere:
const err = new Error("boom");
// Error.captureStackTrace exists in V8-based runtimes (Node.js, Chrome)
// but not in every engine.
Error.captureStackTrace?.(err);
console.log(typeof err.stack); // "string"Async functions
An optional call that is skipped returns undefined, and await undefined simply resolves to undefined. So you can await optional async hooks without extra checks:
async function shutdown(service) {
await service.flush?.();
await service.close?.();
console.log("shut down");
}
shutdown({ close: async () => console.log("closed") });
// closed
// shut downHandling the `undefined` Result
A skipped call evaluates to undefined. A called function may also return undefined. You cannot tell those two cases apart from the result alone:
const a = { run: () => undefined };
const b = {};
console.log(a.run?.()); // undefined (called, returned undefined)
console.log(b.run?.()); // undefined (not called)If your logic depends on whether the function actually ran, check for its presence first instead of inspecting the result. When you just need a usable value, you can supply a fallback with ??, for example formatter.format?.(value) ?? String(value). A later chapter covers that combination in detail.
Quick Reference
| Situation | Recommended form |
|---|---|
| Callback parameter that callers may omit | `callback?.(arg)` |
| Method that some objects implement and others do not | `obj.method?.()` |
| Object that may be absent, method always present if it exists | `obj?.method()` |
| Value from JSON or untrusted input that might not be a function | `typeof v === "function" && v()` |
| Need to know whether the call happened | Explicit `if (fn != null)` check |
Exercise
Given const ui = { onClick: null }; const panel = null;, what does each line do: (a) ui.onClick?.(), (b) ui.onHover?.(), (c) panel.onClick?.(), (d) panel?.onClick?.()?
Show answer
(a) returns undefined because onClick is null. (b) returns undefined because onHover is undefined. (c) throws a TypeError because reading onClick from null fails before the optional call is reached. (d) returns undefined because panel?. short-circuits the whole chain.
Exercise
A settings object loaded from JSON has { "onLoad": true }. Code runs settings.onLoad?.(). What happens, and how should the code be written instead?
Show answer
It throws a TypeError ("settings.onLoad is not a function"), because true is not nullish, so the call goes ahead. Since JSON-derived values can have any type, check the type explicitly: if (typeof settings.onLoad === "function") settings.onLoad();.
Exercise
What is logged by this code? let n = 0; const api = {}; api.track?.(n++); api.log = (x) => x; console.log(api.log?.(n++), n);
Show answer
It logs 0 1. The first call is skipped because api.track is undefined, so n++ is not evaluated and n stays 0. The second call runs: n++ passes 0 and sets n to 1. The function returns 0, and then n is read as 1.