JavaScript

TypeError: callback is not a function in JavaScript

A callback function is a function that is passed as an argument to another function and then invoked from inside the outer function to finish a task or activity. When the callback argument of a function is provided, but the function is called without supplying the callback as a parameter, the “TypeError: callback is not a function in JavaScript” will appear.

This article will demonstrate:

How Does “TypeError: callback is not a function in JavaScript” Occur?

The “TypeError: callback is not a function in JavaScript” occurs when the callback is provided to a function as an argument. Still, the function is called without passing the callback as a parameter.

Example
Here, we will define a function “calculation()” that takes “callback” as a parameter but doesn’t provide a callback when invoking the function:

function calculation(callback){
 return callback();
}

Call the “calculation()” function:

calculation();

The output shows an error:

Let’s see how to fix the above-mentioned error.

How to Fix “TypeError: callback is not a function in JavaScript”?

To solve the specified error, define the callback function using the arrow function and then return it to the defined function:

function calculation(callback = () => {}){
 return callback();
}

Call the function:

calculation();

Or you can define the callback function inside the function call:

calculation(() => {});

It can be observed that the mentioned error has been resolved successfully:

Here, we will perform an addition operation in a callback function by passing two parameters “a” and “b” and then call it by passing two arguments “5” and “8”:

function calculation(callback = (a, b) => {
 var sum = a + b;
 console.log("Sum is: " + sum);
}) {
 return callback(5, 8);
}

Output

That’s how you fix the specified type error.

Conclusion

The “TypeError: callback is not a function in JavaScript” occurs when a function’s callback argument is specified, but the function is called without passing the callback as a parameter. For solving the specified error, define the callback function using the arrow function and then return it to the defined function. This article demonstrated the occurrence and solution for the given error.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.