Call a JavaScript function only if it exists

Let's assume that you have the following function:

javascript
const sum = (a, b, optional) => {

    optional()

    return a + b

}

If you call the function passing 3 arguments:

javascript
sum(2, 3, () => console.log('Start the sum!'))
// Start the sum!
// 5

Now, let's call the function passing 2 arguments:

javascript
sum(2, 3)
// Uncaught TypeError: optional is not a function

To solve the previous error, you could modify the function as follows:

javascript
const sum = (a, b, optional) => {

    if(optional)
        optional()

    return a + b

}

sum(2, 3) // 5

Or you could create a dummy JavaScript function and assign it as initial parameter:

javascript
// You could also:
// optional = Boolean
// optional = () => {}
const sum = (a, b, optional = console.log) => {

    optional()

    return a + b

}

sum(2, 3) // 5

Using console.log() without arguments is similar to use an empty function like const noop = () => {}. You could use the Boolean() method as well.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.