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

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, or a nullish value, this would result in 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

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.