Callback Function in JavaScript
A callback function is a function that is passed as an argument to another function and is called later by that function.
Example:
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("John", sayBye);
Output:
Hello John
Goodbye!
Why Do We Use Callback Functions?
Callbacks are useful when we want to say:
"After this task is completed, execute this function."
This is especially important in JavaScript because JavaScript frequently performs asynchronous operations.
For example:
*Waiting for a timer
*Getting data from a server
*Reading a file
*Handling a button click
*Processing events
Callback vs Normal Function
Normal function:
function add(a, b) {
return a + b;
}
console.log(add(10, 20));
We can directly calling the function.
Callback Function:
function calculate(a, b, callback) {
let result = a + b;
callback(result);
}
calculate(10, 20, function(result) {
console.log(result);
});
Here the function is passed to another function.
Top comments (0)