Callback
Functions
Learn how JavaScript uses functions as arguments to build powerful, flexible, and asynchronous code patterns.
What Is a Callback Function?
A callback function is a function that you pass as an argument to another function. The receiving function "calls back" (invokes) the passed function at the right time.
Functions Are Values
Before understanding callbacks, you must know that functions in JavaScript can be treated like any other data. You can assign them to variables, store them in arrays, or hand them to other functions.
The Callback Pattern
The Core Rule
Synchronous vs Asynchronous
Named vs Anonymous Callbacks
Arrow Functions as Callbacks
ES6 introduced arrow functions, which provide a shorter syntax for anonymous callbacks. They are the most common way to write callbacks in modern JavaScript.
How to Write a Callback
Example 1: forEach
Array.forEach() is a built-in method that accepts a callback. It calls your function once for each element in the array.
Example 2: setTimeout
setTimeout() is an asynchronous host function. It schedules your callback to run after a delay.
Example 3: Event Listeners
The addEventListener method on DOM elements uses callbacks. Your function runs whenever the specified event occurs.
Passing Data to Callbacks
Host functions often pass data into your callback as arguments. You define parameters to receive them.
Common Callback Patterns
Common Mistakes
Callback Comparison Table
| Synchronous | Asynchronous | |
|---|---|---|
| Timing | Runs immediately | Runs later |
| Blocks execution? | Yes | No |
| Examples | forEach, map, filter | setTimeout, fetch, addEventListener |
| Use case | Data transformation | I/O, timers, events |
| Execution order | Predictable | Depends on trigger |
Question 1 of 5
What is a callback function?
Question 2 of 5
Consider this code:
console.log("A");
setTimeout(function() {
console.log("B");
}, 0);
console.log("C");
What is the output order?
Question 3 of 5
What is wrong with this code?setTimeout(greet(), 1000);
Question 4 of 5
Which array method does not use a callback?
Question 5 of 5
Consider this code:
function process(x, callback) {
const result = x * 2;
callback(result);
}
process(5, function(val) {
console.log(val);
});
What is logged to the console?