A callback function is a function passed as an argument to another function so that it can be called later.
function greet(name) {
console.log("Hello " + name);
}
function user(callback) {
callback("Sajin Joe");
}
user(greet);
Output:
Hello Sajin Joe
Callback with a simple calculation
function calculate(a, b, callback) {
console.log(callback(a, b));
}
function add(x, y) {
return x + y;
}
calculate(10, 20, add);
Output:
30
Callback with setTimeout()
setTimeout(function() {
console.log("Hello JavaScript");
}, 2000);
Output: Hello JavaScript after approximately 2 seconds.
The function passed to setTimeout() is a callback. The timer schedules it to run later.
Top comments (0)