How to Use JavaScript Optional Chaining to Make a Function Call?

Using optional chaining to make function calls

You can safely call a function with optional chaining (?.), which would return undefined if the given function does not exist. To do so, you can use either of the following syntax (based on whether the function exists in an object or an array):

// ES11+
obj.methodName?.()
array[index]?.()

For example, you can make an object method call with optional chaining in the following way:

// ES11+
const obj = {
    foo: function () {
        console.log('called');
    },
    bar: null,
    baz: undefined,
};

obj.foo?.(); // 'called'

obj.bar?.(); // undefined
obj.baz?.(); // undefined
obj.nonExistent?.(); // undefined

Similarly, you can make a call to a function in an array with optional chaining in the following way:

// ES11+
const arr = [
    function () {
        console.log('called');
    },
    null,
    undefined,
];

arr[0]?.(); // 'called'

arr[1]?.(); // undefined
arr[2]?.(); // undefined
arr[50]?.(); // undefined

As long as the value is evaluated to a nullish value (i.e. null or undefined), the result would evaluate to undefined. However, for any other value, that's not a function, this would return a TypeError. For example, consider the following:

// ES11+
const obj = { foo: 'bar' };

obj.foo?.(); // TypeError: obj.foo is not a function
// ES11+
const arr = [ 'foo' ];

arr[0]?.(); // TypeError: arr[0] is not a function

Hope you found this post useful. It was published . Please show your love and support by sharing this post.