01 / 21

Callback
Functions

Learn how JavaScript uses functions as arguments to build powerful, flexible, and asynchronous code patterns.

JavaScript

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.

// Assigning a function to a variable const greet = function(name) { return "Hello, " + name; }; // Passing that variable like any value console.log(greet("Alice")); // "Hello, Alice"

The Callback Pattern

doWork(callback) The "host" function invokes callback() Your function yourCode() Passes function in passes callback defines callback

The Core Rule

// A function that accepts a callback function doSomething(callback) { // ... do some work ... callback(); // invoke the callback } // Usage: pass a function as the argument doSomething(function() { console.log("Done!"); });
1
Declare a host function that has a parameter for the callback.
2
Inside the host, call that parameter like a regular function.
3
When calling the host, pass a function (named or anonymous) as the argument.

Synchronous vs Asynchronous

Synchronous Step 1: call host() Step 2: callback() runs Step 3: next line Runs in order, blocks Asynchronous Step 1: call host(cb) Step 2: next line (no wait) Later: callback() fires Non-blocking, deferred

Named vs Anonymous Callbacks

Named Callback
Defined separately, then passed by name. Easier to debug and reuse.
Anonymous Callback
Defined inline at the call site. More concise, but harder to debug in stack traces.
// Named callback function onDone() { console.log("Finished"); } doWork(onDone); // Anonymous callback doWork(function() { console.log("Finished"); });

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.

// Traditional anonymous function setTimeout(function() { console.log("Hello"); }, 1000); // Arrow function (same behavior) setTimeout(() => { console.log("Hello"); }, 1000);

How to Write a Callback

1
Identify the task: What should happen after some operation?
2
Write the callback: Create a function that performs that task.
3
Pass it in: Hand the function (without parentheses) to the host function.
4
Trust the host: The host function decides when and how to call your callback.
5
Handle arguments: Check if the host passes data (like event or error) to your 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.

const fruits = ["apple", "banana", "cherry"]; fruits.forEach(function(fruit, index) { console.log(index + ":\ " + fruit); }); // Output: // 0: apple // 1: banana // 2: cherry

Example 2: setTimeout

setTimeout() is an asynchronous host function. It schedules your callback to run after a delay.

console.log("Start"); setTimeout(() => { console.log("This runs later"); }, 2000); console.log("End"); // Output: // Start // End // This runs later (after 2 seconds)

Example 3: Event Listeners

The addEventListener method on DOM elements uses callbacks. Your function runs whenever the specified event occurs.

const btn = document.querySelector("#myBtn"); btn.addEventListener("click", function(event) { console.log("Button clicked!"); console.log(event.target); });

Passing Data to Callbacks

Host functions often pass data into your callback as arguments. You define parameters to receive them.

function fetchUser(id, callback) { // Simulate getting user data const user = { id: id, name: "Alice" }; callback(user); // pass data to callback } fetchUser(42, function(user) { console.log(user.name); // "Alice" });

Common Callback Patterns

Array Methods
forEach, map, filter, reduce: all take callbacks that process each element.
Timers
setTimeout and setInterval: schedule callbacks to run after a delay or repeatedly.
Event Handling
addEventListener: callbacks fire in response to user actions like clicks, keypresses, etc.

Common Mistakes

✕ Calling Instead of Passing
Writing doWork(myFunc()) calls myFunc immediately and passes its return value, not the function itself. Use doWork(myFunc) instead.
✕ Forgetting Async Order
Assuming code after setTimeout waits for the callback. It does not: JavaScript continues executing immediately.
✕ Ignoring Callback Arguments
Not defining parameters in your callback to receive data the host passes (like event, error, or element).

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

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

What is logged to the console?