What is a Callback Function?
A callback function is a function that we pass as an argument to another function so that the receiving function can call it when it needs to.
In other words one function can receive another function and decide when that function should be executed.
Example:
function greet() {
console.log("hello"):
}
function welcome(callback) {
callback();
}
welcome(greet);
Here "greet" is passed to "welcome()" as an argument.
welcome(greet);
Inside the "welcome()" function we receive it through the "callback" parameter:
function welcome(callback) {
callback();
}
When we write:
callback();
JavaScript executes the "greet()" function.
Why Do We Use Callback Functions?
The main reason we use a callback is that we don't always want to decide inside a function what should happen next.
Instead, we can give the function another function and say:
After you finish your work call this function.
For example one function can perform some work and after that work is completed it can call the function that was passed to it.
This makes the code more flexible because we can change the function we pass as the callback without changing the main function.
What Happens When We Pass an Argument?
When we do:
welcome(greet);
the "greet" function is passed into the "callback" parameter.
So we can think of it like this:
welcome(greet)
↓
callback = greet
↓
callback()
↓
greet()
Finally "greet()" gets executed.
What Happens If We Don't Pass the Callback?
If the function expects a callback:
function welcome(callback) {
callback();
}
but we call it like this:
welcome();
then there is no function inside "callback".
So when JavaScript reaches:
callback();
it cannot execute it because "callback" is "undefined".
That results in an error.
What About 2, 3, 4 or 5 Functions?
The number of functions does not decide whether an argument is required.
Even with just two functions if one function is passed to another function we use an argument:
function greet() {
console.log("Hello");
}
function welcome(callback) {
callback();
}
welcome(greet);
Here "greet" is the callback and it is passed as an argument.
The same idea can continue with 3, 4, 5, or more functions.
For example:
Function 1
↓
passes Function 2
↓
Function 2
↓
passes Function 3
↓
Function 3
↓
passes Function 4
↓
Function 4
In this kind of chain, each function that needs to receive the next function has to receive it somehow — commonly as an argument.
So the important rule is not:
"More functions = callback argument."
The actual rule is:
When one function is passed into another function the passed function is the callback.

Top comments (0)