DEV Community

Arun Prakash Pandey
Arun Prakash Pandey

Posted on

Conditional Method Invocation in Js

The previous post was related to conditional access of properties in javascript objects. In this post, we will deal with conditional invocation of methods.

What is invocation ?

An invocation expression is JavaScript’s syntax for calling (or
executing) a function or method.
You must declare a function before invocation.

f(0);
Math.max(x,y);
[a,b,c].sort();
Enter fullscreen mode Exit fullscreen mode

What is conditional invocation of a function ?

A function can be invoked using ?.() instead of (). If the expression to the left of the parentheses is null or undefined or any other non-function, a TypeError is thrown.
Note that conditional property access is used to gracefully handle Type Errors.
This concept of conditional invocation of method is based on the same ground.
With the ?.() invocation syntax, if the expression to the left of the ?. evaluates to null or undefined, then the entire invocation expression evaluates to undefined and no exception is thrown.

A Deep Dive

A function invocation checks and verifies the left side of the parenthesis before executing the body of the function.

If the value of the function expression is not a function, a TypeError is thrown.
So, it is important to understand that ?.() only checks whether the lefthand side is null or undefined. It does not verify that the value is actually a function.
Like conditional property access expressions, function invocation with ?.() is short-circuiting: if the value to the left of ?. is null or undefined, then none of the argument expressions within the parentheses are evaluated.
For Example:

o.m() // Regular property access, regular invocation
o?.m() // Conditional property access, regular invocation
o.m?.() // Regular property access, conditional invocation
Enter fullscreen mode Exit fullscreen mode

Please Note that it can still give Type Error after conditional invocation if the property / method is not a function as per definition in Js.
Next post will touch on Operators, their precedence and order of execution.
Thank you for reading this post, you're welcome to share feedback.

Top comments (0)