How does the optional chaining call syntax (?.()) differ from just optional property access, and when is it needed?
Short answer
?.() specifically guards against the FUNCTION ITSELF being null/undefined before attempting to call it — necessary when a property might hold an optional callback function; plain ?. alone only guards property access, not the act of invoking what it resolves to.
Advertisement
AModel answer
?.() specifically guards against the FUNCTION ITSELF being null/undefined before attempting to call it — necessary when a property might hold an optional callback function; plain ?. alone only guards property access, not the act of invoking what it resolves to.
interface Options {
onComplete?: () => void;
}
function run(options: Options) {
options.onComplete?.(); // safely calls onComplete only if it was actually provided
}Real-world example
Safely invoking an optional callback prop or event handler that a caller may or may not have supplied.
Likely follow-ups
- Does optional chaining also work with array/bracket-style indexing, like arr?.[0]?
Related topics