JAVASCRIPT

JavaScript Callback Function: Syntax, Usage, and Examples

A JavaScript callback function is a function that you pass as an argument to another function. The receiving function then calls (or "executes") the callback at a specific time. Callbacks allow for better code organization and enable asynchronous programming.

Quick Answer: What is a JS Callback Function?

A callback is a function passed as an argument to another function, which is then invoked inside the outer function to complete some kind of routine or action. It allows us to control the order of execution, especially for asynchronous tasks like fetching data or setting timers.

Synchronous Example (Runs Immediately):

function greet(name, callback) {
  console.log('Hello, ' + name);
  callback(); // The callback is executed right after the log
}

function sayGoodbye() {
  console.log('Goodbye!');
}

greet('Alice', sayGoodbye);
// Output:
// Hello, Alice
// Goodbye!

Asynchronous Example (Runs Later):

console.log('Start');

setTimeout(function() {
  // This anonymous function is the callback
  console.log('This runs after 2 seconds');
}, 2000);

console.log('End');
// Output:
// Start
// End
// This runs after 2 seconds

Callbacks are the foundational concept for handling asynchronous operations in JavaScript.

How to Use a JavaScript Callback Function

You define a function and pass another function as an argument. The receiving function then calls the callback when needed.

Basic Syntax

function mainFunction(callback) {
  console.log("Main function is running...");
  callback(); // Call the callback function
}

function callbackFunction() {
  console.log("Callback function executed.");
}

mainFunction(callbackFunction);

Here, callbackFunction is passed to mainFunction, which then executes it.

Callback Function with Parameters

You can also pass arguments to the callback function.

function greet(name, callback) {
  console.log(`Hello, ${name}!`);
  callback();
}

function done() {
  console.log("Greeting completed.");
}

greet("Alice", done);

The callback done runs after greet prints a message.

When to Use a JavaScript Callback Function

  1. Asynchronous Operations – Callbacks help execute code only when an asynchronous task (like a network request) completes.
  2. Event Handling – JavaScript uses callbacks for handling user interactions, such as button clicks.
  3. Reusability and Modularity – Callbacks allow you to create more flexible and reusable functions.

Examples of JavaScript Callback Functions

Handling Asynchronous Code

You often use callbacks with setTimeout for delaying code execution.

function delayedMessage(callback) {
  setTimeout(() => {
    console.log("This message appears after 2 seconds.");
    callback();
  }, 2000);
}

function done() {
  console.log("Callback executed after delay.");
}

delayedMessage(done);

Callbacks in Event Listeners

Event listeners rely on callbacks to execute functions when an event occurs.

document.getElementById("btn").addEventListener("click", function () {
  console.log("Button clicked!");
});

The anonymous function acts as a callback and runs when you click the button.

Callback Hell

When multiple callbacks are nested, it leads to callback hell, making the code harder to read and maintain.

getUser(function (user) {
  getOrders(user, function (orders) {
    getPaymentDetails(orders, function (details) {
      processPayment(details, function () {
        console.log("Payment completed.");
      });
    });
  });
});

You can replace this with Promises or async/await for cleaner code.

Learn More About JavaScript Callback Functions

Using Anonymous Callback Functions

Instead of defining a separate function, you can use an anonymous function as a callback.

setTimeout(function () {
  console.log("Anonymous function executed.");
}, 1000);

Async Callback Function

When working with asynchronous operations, passing a callback function ensures the task completes before executing the next step.

function fetchData(url, callback) {
  setTimeout(() => {
    console.log(`Fetched data from ${url}`);
    callback();
  }, 1500);
}

fetchData("https://api.example.com", () => {
  console.log("Processing fetched data...");
});

Passing Arguments to a Callback

You can pass arguments when calling a callback function.

function processData(data, callback) {
  console.log(`Processing: ${data}`);
  callback(data);
}

function logData(info) {
  console.log(`Logged: ${info}`);
}

processData("User Info", logData);

Avoiding Callback Hell with Promises

To avoid deeply nested callbacks, use Promises.

function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Data received");
    }, 2000);
  });
}

fetchData().then((data) => console.log(data));

This structure improves readability and maintainability.

How to Add a Callback Function in JavaScript

To add a callback function, define the function and pass it as an argument when calling another function.

function executeTask(task, callback) {
  console.log(`Executing: ${task}`);
  callback();
}

executeTask("Download File", function () {
  console.log("Download completed.");
});

Callback Function vs. Regular Function

A regular function executes immediately when called. A callback function, on the other hand, runs when another function invokes it.

function regularFunction() {
  console.log("Runs immediately.");
}

function callbackExample(callback) {
  console.log("Preparing to execute callback...");
  callback();
}

callbackExample(regularFunction);

Using Callbacks in Loops

Callbacks also help process arrays using methods like map, filter, and forEach.

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function (num) {
  console.log(`Number: ${num}`);
});

Handling Errors in Callback Functions

You should always handle errors inside callbacks to prevent unexpected behavior.

function fetchData(url, callback) {
  setTimeout(() => {
    const error = false; // Simulating no error
    if (error) {
      callback("Error occurred", null);
    } else {
      callback(null, `Data from ${url}`);
    }
  }, 1000);
}

fetchData("https://api.example.com", function (err, data) {
  if (err) {
    console.error(err);
  } else {
    console.log(data);
  }
});

JavaScript Callback Function Use Cases

  1. Managing Asynchronous Code – Callbacks handle API requests, file reading, and database queries.
  2. Event-Driven Programming – Many JavaScript features, like event listeners, depend on callbacks.
  3. Code Reusability – Passing different callback functions makes your code more flexible.

Callbacks form the foundation of JavaScript's asynchronous programming. Understanding how to use them effectively will help you write better, more efficient code.

Looking to dive deeper into the JavaScript callback function and other essential JavaScript concepts? Check out our JavaScript course.

Key Takeaways for JavaScript Callbacks

  • Function as an Argument: A callback is simply a function that is passed into another function as an argument.
  • "Call Me Back Later": The name "callback" comes from the idea that the outer function will "call you back" later when it has finished its job.
  • Enables Asynchronous Behavior: Callbacks are essential for non-blocking operations, ensuring that code runs only after a task (like a network request) is complete.
  • Beware of Callback Hell: Deeply nested callbacks make code difficult to read and debug. This is a sign that you should refactor your code to use modern alternatives.
  • Modern Alternatives Exist: While fundamental to understand, most modern asynchronous code is written with Promises and Async/Await for better readability and error handling.
Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH

Reach your coding goals faster