Callback Functions
A callback is a function passed as an argument to another function, to be called later. Callbacks are foundational to JavaScript — used in event handlers, array methods, timers, and async operations.
Callbacks Explained
- Callback — A function passed to another function as an argument
- Why — Let functions be customizable: same loop, different action for each element
- Synchronous callbacks — Run immediately: array.forEach(callback), array.map(callback)
- Asynchronous callbacks — Run later: setTimeout(callback, 1000), addEventListener(callback)
- Higher-order function — A function that takes or returns another function
- Callback hell — Too many nested callbacks become unreadable (solved by Promises in Module 8)
Callbacks Code
// Callback basics
function processData(data, callback) {
const result = callback(data);
console.log("Result:", result);
}
processData(5, function(n) { return n * 2; }); // Result: 10
processData(5, n => n ** 2); // Result: 25
// Array methods use callbacks
const numbers = [1, 2, 3, 4, 5];
// forEach — do something with each item
numbers.forEach((num, index) => {
console.log(`#${index}: ${num}`);
});
// map — transform each item
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter — keep items matching condition
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
// Async callback — runs after 1 second
setTimeout(() => {
console.log("This runs after 1 second!");
}, 1000);
// Real-world: custom sort
const users = [
{ name: "Charlie", age: 28 },
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
];
users.sort((a, b) => a.age - b.age); // callback determines sort order
console.log(users); // sorted by age ascendingTip
Tip
Use arrow functions for callbacks to keep code concise: numbers.filter(n => n > 5).map(n => n * 2). Chain array methods for powerful data transformations in a single, readable expression.
async/await reads like sync code — the modern standard
Common Mistake
Warning
Deeply nested callbacks create 'callback hell' — hard to read and debug. If your code indents more than 3 levels deep with callbacks, refactor to Promises or async/await (covered in Module 8).
Practice Task
Note
Practice callbacks: (1) Write a function that takes an array and a callback, applying the callback to each element. (2) Use it with different callbacks: double, square, capitalize. (3) Write a custom sort callback that sorts users by age.
Quick Quiz
Key Takeaways
- A callback is a function passed as an argument to another function, to be called later.
- Callback — A function passed to another function as an argument
- Why — Let functions be customizable: same loop, different action for each element
- Synchronous callbacks — Run immediately: array.forEach(callback), array.map(callback)