← Back to Chapters

JavaScript Callbacks

⚙️ JavaScript Callbacks

⚡ Quick Overview

A callback is a function that is passed as an argument to another function and is executed after that function finishes its work. Callbacks are a core part of JavaScript, especially for handling asynchronous operations like timers, user input, and network requests.

Because functions in JavaScript are first-class citizens, you can store them in variables, pass them as parameters, and call them later — this is exactly what callbacks do.

? Key Concepts

  • Callback function: A function passed into another function as an argument.
  • Execution order: Callbacks help you run code only after some other work is complete.
  • Synchronous vs asynchronous: Callbacks can be used in both, but are especially useful in asynchronous code (like setTimeout()).
  • Anonymous callbacks: Functions without a name, often used directly where needed.
  • Array methods: Methods like forEach() use callbacks to process each element.
  • Custom handlers: You can design your own functions that accept callbacks to customize behavior.

? Syntax and Theory

A typical pattern for using callbacks in JavaScript looks like this:

? Basic Callback Pattern
function doSomething(callback) {
  // some work here...
  callback(); // call the function passed in
}

function myCallback() {
  console.log("Callback was called!");
}

doSomething(myCallback);

Here, myCallback is passed to doSomething without parentheses, meaning we are passing the function itself, not its return value. Inside doSomething, we can call it using callback() whenever we want.

? Code Examples

? Basic Callback Example

A simple example where a callback is used to greet a user after getting their name.

? View Basic Callback Code
function greet(name) {
  alert('Hello, ' + name);
}

function processUserInput(callback) {
  const name = prompt('Please enter your name:');
  callback(name);
}

processUserInput(greet);

Here, greet is passed to processUserInput as a callback and is executed after the user enters their name.

⏱️ Callback with setTimeout (Asynchronous)

Callbacks are commonly used with asynchronous functions like setTimeout() to delay execution.

? View setTimeout Example
function displayMessage() {
  console.log("This message appears after 2 seconds");
}

setTimeout(displayMessage, 2000);

? Anonymous Callback Function

Sometimes you don’t need to reuse a callback, so you can define it anonymously.

? View Anonymous Callback Example
setTimeout(function () {
  console.log("Hello from an anonymous callback!");
}, 1000);

? Callback with Parameters

Callbacks can receive parameters, allowing you to pass data into them.

? View Callback with Parameters Example
function greetUser(name) {
  console.log("Hello, " + name);
}

function getUserInput(callback) {
  const user = "Alice";
  callback(user);
}

getUserInput(greetUser);

? Callback in Array Iteration

Array methods like forEach() use callbacks to perform operations on each item.

? View Array Callback Example
const numbers = [1, 2, 3, 4];

numbers.forEach(function (num) {
  console.log(num * 2);
});

?️ Creating a Custom Callback Handler

You can design functions that accept callbacks to customize what happens after a task.

? View Custom Callback Handler Example
function doTask(taskName, callback) {
  console.log("Starting task: " + taskName);
  callback();
}

function finish() {
  console.log("Finished task!");
}

doTask("Download file", finish);

? Live Output / Explanation

If you run the examples above in the browser console or an editor:

  • The basic callback example will show a prompt asking for your name, then an alert greeting you.
  • The setTimeout examples will log messages to the console after a delay (1 or 2 seconds), demonstrating asynchronous behavior.
  • The forEach example will log 2, 4, 6, 8 to the console, doubling each number in the array using a callback.
  • The custom callback handler example will log: "Starting task: Download file" and then "Finished task!", showing how callbacks can signal completion.

? Use Cases / When to Use Callbacks

  • When you want code to run only after another piece of code has finished.
  • When dealing with asynchronous tasks: timers, network requests, file operations, etc.
  • When you want to make a function reusable and customizable via different callbacks.
  • When iterating over arrays and applying logic to each element (e.g., forEach, map).

? Tips & Best Practices

  • Use callbacks to ensure code runs in a specific, predictable order.
  • Always check if a value is a function before calling it (e.g., if (typeof callback === "function") callback();).
  • You can use named or anonymous functions as callbacks depending on reuse and readability.
  • Use arrow functions for cleaner callback syntax when appropriate.
  • Avoid deeply nested callbacks; consider splitting logic into smaller functions or using promises/async–await in modern code.

? Interactive Callback Demo

Click the button below to see a simple callback in action. The main function will perform a task and then call the callback to update the message.

? Demo Result

Click the button to start the task and run the callback.

? Practice Tasks

  • Write a function that takes a number and a callback, and doubles the number using the callback.
  • Use setTimeout with a callback to simulate a loading screen.
  • Write a loop using forEach() to apply a callback to each item in an array.
  • Create a function that accepts two numbers and a callback, and uses the callback to add or multiply them.
  • Demonstrate how to handle errors in a callback function (for example, if the input is invalid).
  • Use an arrow function as a callback in an array method.
  • Write a function that takes a string and a callback, and uses the callback to transform the string to uppercase.
  • Show how to pass additional arguments to a callback function (e.g., message + data).