JavaScript Callback Functions
A callback function is a function passed as an argument to another function, and it is executed after the outer function completes. Callbacks are fundamental in async programming (like API calls, event handling, and timers).
1. What Is a Callback Function?
A callback is not immediately executed. It’s “called back” later when something is done.
Example:
function greet(name, callback) {
console.log("Hello,
" + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("Alice"
, sayBye);
Output
Hello, Alice
Goodbye!
Goodbye!
2. Callback as an Anonymous Function
You can pass a function inline as a callback.
function processNumber(num, callback) {
console.log("Number is:"
, num);
callback(num);
}
processNumber(5, function(n) {
console.log("Squared:"
, n * n);
});
Output
Number is: 5
Squared: 25
Squared: 25
3. Real-World Example: Using setTimeout
Example:
setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);
This is a callback used for asynchronous delay.
4. Array Method Callback – forEach
Many built-in methods use callbacks.
Example:
let fruits = ["apple", "banana", "mango"
fruits.forEach(function(fruit) {
console.log("I like", fruit);
});
Output
I like apple
I like banana
I like mango
I like banana
I like mango
5. Callback with Arrow Function
Example:
function calculate(a, b, callback) {
let result = a + b;
callback(result);
}
calculate(3, 4, (res) => {
console.log("Sum is:"
, res);
});
Output
csharp
CopyEdit
Sum is: 7
CopyEdit
Sum is: 7
6. Named vs Anonymous Callback
function showResult(result) {
console.log("Result:"
, result);
}
function multiply(a, b, callback) {
let result = a * b;
callback(result);
}
multiply(2, 5, showResult); // Result: 10
Why Use Callback Functions?
- Reuse logic by passing different functions
- Handle async code (e.g., timers, events, APIs)
- Used in higher-order functions (like map, filter, reduce)
- Basis for Promises and async/await