Functions as Arguments
A callback is a function passed into another function.
The receiver decides when to call it.
JavaScript Tutorial
A callback is a function passed into another function to be called later.
They are essential for async operations and array methods.
Callbacks let you control when code runs, which is vital for events and async tasks.
Understanding callbacks is a foundation for promises and async/await.
function doWork(callback) { ... }
doWork(() => { ... })function run(task) {
task();
}
run(() => console.log("Done"));Pass a function to be called later.
const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);
console.log(doubled);Array methods rely heavily on callbacks.
A callback is a function passed into another function.
The receiver decides when to call it.
Callbacks are common in asynchronous code like timers and event handlers.
They allow you to run logic after an async operation completes.
Deeply nested callbacks can hurt readability.
Consider promises or async/await for complex flows.
Without
const nums = [1, 2, 3];
const doubled = [];
for (const n of nums) {
doubled.push(n * 2);
}With
const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);Refactor into named functions or use async/await.
Use error-first callbacks or try/catch where appropriate.
Ensure the callback is called once per operation.
A function passed to another function to be executed later.
They allow logic to run after an async task completes.
Use named functions or switch to promises and async/await.
Practice: Write a function that accepts a callback and runs it twice.
// TODO: function repeat(fn)
One Possible Solution
function repeat(fn) {
fn();
fn();
}
repeat(() => console.log("Hi"));A function passed to another function to be executed later.
No, they are also used for sync patterns like array methods.
Nested callbacks that are hard to read and maintain.
Try passing different callbacks to the function.