Last updated: Mar 3, 2024
Reading time·2 min
The "TypeError: callback is not a function" error occurs when we define a
callback
parameter to a function but invoke the function without passing a
callback.
To solve the error, specify a function as a default parameter, or always provide a parameter when calling the function.
Here is an example of how the error occurs.
function example(callback) { return callback(); } // ⛔️ TypeError: callback is not a function example();
callback
as a parameter but didn't provide a callback when calling the function.To solve the error, make sure to always provide a callback when calling the function.
function example(callback) { return callback(); } // ✅ Works example(() => { console.log('success'); });
We passed an arrow function callback when calling the example
function, but
you can also use a named function.
function example(callback) { return callback(); } function logMessage() { console.log('success'); } // ✅ Works example(logMessage);
callback
parameterAlternatively, 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.
function example(callback = () => {}) { return callback() } // ✅ Works example();
We used a function that doesn't do anything as the default value for the
callback
parameter.
When the function is called without a callback being provided, the default value of an empty function is used.
You can also use any other function as the default parameter depending on your use case.
function example(callback = defaultFunc) { return callback(); } function defaultFunc() { console.log('success'); } // ✅ Works example(); // 👉️ success
Perhaps, an even better approach is to check if the callback was provided before calling it in the function.
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
.
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.
You can learn more about the related topics by checking out the following tutorials: