TypeError: callback is not a function in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

TypeError: callback is not a function in JavaScript #

The "callback is not a function" error occurs when we define a callback parameter to a function, but invoke the function without passing a callback as a parameter. To solve the error, provide a function as a default parameter, or always provide a parameter when calling the function.

typeerror callback is not a function

Here is an example of how the error occurs.

index.js
function example(callback) { return callback(); } // ⛔️ TypeError: callback is not a function example();
We defined a function that takes a callback as a parameter but didn't provide a callback when invoking the function.

To solve the error, make sure to always provide a callback when calling the function.

index.js
function example(callback) { return callback(); } // ✅ Works example(() => {});

Alternatively, you can define a default value for the callback parameter. This way you won't get an error even if no parameter is provided when calling the function.

index.js
function example(callback = () => {}) { return callback() } // ✅ Works example();

Perhaps, an even better approach is to check if the callback was provided before calling it in the function.

index.js
function example(callback) { if (typeof callback === 'function') { return callback() } } // ✅ Works example();

The typeof operator allows us to check if the callback variable stores a function.

We only call the callback if it is provided and has a type of function.

If the error persists, console.log the callback variable and its type, e.g. console.log(typeof callback).

Make sure that the variable stores a function before calling it.

You might be declaring a variable named callback that shadows the value of a function you're trying to invoke.

Make sure you're spelling callback correctly, as variable names are case sensitive.

Conclusion #

The "callback is not a function" error occurs when we define a callback parameter to a function, but invoke the function without passing a callback as a parameter. To solve the error, provide a function as a default parameter, or always provide a parameter when calling the function.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.