Solve - callback is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Matt Collamer

Solve - callback is not a function Error #

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 named example 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 invoking the function.

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

Alternatively, you can define a default value for the callback parameter. This way even if you don't provide a parameter when invoking the function, you won't get an error.

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 you're still getting the error, 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 in JavaScript.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee