Oliver Jumpertz

Optional Chaining With Functions

Category: JavaScript

Share this snippet to:

// Yes, the syntax is correct
const result = obj?.nested?.func?.();

Explanation

Optional chaining treats functions like any other parameter. This means, that you can, theoretically (especially in this case), access a function call like a property. If you place the question mark before the dot and the parantheses behind it, the function will indeed only ever be called if the whole chain is present. Otherwise, your result will just be undefined, which is something you can handle however you see it fitting.


Share this snippet to: