Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP W3.CSS C C++ C# HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

JS Tutorial

JS Home JS Introduction JS Where To JS Output JS Syntax JS Operators JS If Conditions JS Loops JS Strings JS Numbers JS Functions JS Objects JS Scope JS Dates JS Temporal  New JS Arrays JS Sets JS Maps JS Iterations JS Math JS RegExp JS Data Types JS Errors JS Debugging JS Style Guide JS Reference JS Projects  New JS Versions JS HTML DOM JS HTML Events JS HTML First

JS Advanced

JS Functions JS Objects JS Classes JS Asynchronous JS Modules JS Meta & Proxy JS Typed Arrays JS DOM Navigation JS Windows JS Web API JS AJAX JS JSON JS jQuery JS Graphics JS Examples JS Reference


JavaScript Callbacks

"I will call back later!"

A callback is a function passed as an argument to another function.

The receiving function decides when to use (call) the callback.

A callback can be called immediately, later, once, or many times.

By themselves, callbacks are neither synchronous nor asynchronous.

They are simply a way to let one function execute another function.

Why Use Callbacks?

Callbacks make functions more flexible.

Instead of hardcoding what should happen next, a function can let the caller decide by supplying a callback.

Example

Pass a function as an argument:

// A Greet Function
function greet(name, callback) {
  callback("Hello " + name);
}

// A Display Function
function display(message) {
  document.getElementById("demo").innerHTML = message;
}

// Call greet() with a callback function (display)
greet("John", display);
Try it Yourself »

The display function is the callback.

The greet() function decides when to call it.


Synchronous Callbacks

Most callbacks execute immediately.

These are called synchronous callbacks because they run before the current function returns.

Example

// Calculate Function
function calculate(x, y, operation) {
  return operation(x, y);
}

// Add Function
function add(a, b) {
  return a + b;
}

// Call calculate() with add as callback
let result = calculate(5, 3, add);
Try it Yourself »

Note

The callback runs immediately while calculate() is executing.

No asynchronous behavior is involved.


Built-in Synchronous Callbacks

Many JavaScript methods use synchronous callbacks.

Method Callback Called Asynchronous?
forEach() Once for each element No
map() Once for each element No
filter() Once for each element No
reduce() For each element No
sort() To compare values No

Timing Problems

You cannot see a result before it is computed.

Example

let result;

setTimeout(function() {
  result = 5;
}, 1000);

// What is result here?
Try it Yourself »

The result is undefined because the async code has not finished yet.


The Callback Idea

The solution to the problem above, is to give JavaScript a callback function to call after the result is ready.

A callback is a function passed as an argument to another function.

This technique allows a function to call another function.

Example

function done(value) {
  myDisplayer(value);
}

setTimeout(function() {
  done(5);
}, 1000);

// What is result here?
Try it Yourself »

The value is used inside the callback.

This works because the callback runs later.


Asynchronous Callbacks

Callbacks are also commonly used with asynchronous APIs.

In these cases, the callback runs after the asynchronous operation has completed.

The callback is not what makes the operation asynchronous.

The asynchronous API decides when to call the callback.

Example

// Set a Timeout
setTimeout(function () {myDisplayer("Finished!")}, 3000);
Try it Yourself »

In the example above:

myDisplayer is a callback function passed as an argument to setTimeout().

3000 is the number of milliseconds before myDisplayer will be called.

The browser waits three seconds before calling the callback.

The delay is created by setTimeout(), not by the callback itself.

Note

When you pass a function as an argument, remember not to use parenthesis.

Right: setTimeout(myFunction, 3000)

Wrong: setTimeout(myFunction(), 3000)



Event Handling

Callbacks are often used in JavaScript, especially in event handling:

User interactions, such as button clicks or key presses, can be handled by providing a callback function to an event listener.

Example

document.getElementById("myButton").addEventListener("click", displayDate);
Try it Yourself »

In the example above, displayDate is a callback function passed as an argument to the addEventListener() method.

displayDate will be called when a user clicks the button with id="myButton".


Sequence Control

Sometimes you would like to have better control over when to execute a function.

Suppose you want to do a calculation, and then display the result.

You could first call the calculator function myCalculator, and then call the display function myDisplayer:

Example

// Funtion to display something
function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

// Function to calculate a sum
function myCalculator(num1, num2) {
  let sum = num1 + num2;
  return sum;
}

// Call the calculator
let result = myCalculator(5, 5);

// Call the displayer
myDisplayer(result);

Try it Yourself »

Or, you could call the calculator function myCalculator, and let the calculator function call the display function myDisplayer:

Example

// Funtion to display something
function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

// Function to calculate a sum
function myCalculator(num1, num2) {
  let sum = num1 + num2;
  myDisplayer(sum);
}

// Call the calculator
myCalculator(5, 5);

Try it Yourself »

The problem with the first example above, is that you have to call two functions to display the result.

The problem with the second example, is that you cannot prevent the calculator function from displaying the result.

Now it is time to bring in a callback.


Using a callback, you could call the calculator function (myCalculator) with a callback (myCallback), and let the calculator function run the callback after the calculation is finished:

Example (Callbacks)

function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum);
}

myCalculator(5, 5, myDisplayer);
Try it Yourself »

In the example above, myDisplayer is used as a callback function.

It is passed to myCalculator() as an argument.


Callback Chains

Sometimes one callback starts another operation that uses another callback.

This can lead to deeply nested, complex and hard-to-read code.

When callbacks get deep, debugging is difficult. The logic moves from left to right and becomes difficult to follow.

This is often referred to as "callback hell" or the "pyramid of doom".

Example

step1(function(result1) {
  step2(result1, function(result2) {
    step3(result2, function(result3) {
      display(result3);
    });
  });
});

Note

Promises and async/await were introduced to make asynchronous code easier to read and maintain.


Summary

  • A callback is a function passed to another function.
  • Callbacks can be synchronous or asynchronous.
  • The callback itself does not make code asynchronous.
  • Many JavaScript methods use synchronous callbacks.
  • Asynchronous APIs often use callbacks to handle results.
  • Promises and async/await build on the same idea while making asynchronous code easier to write.

Callback is Not Asynchronous

  • A callback is just a function.
  • It may be called immediately (like map() or sort()).
  • It may be called later by an asynchronous API (like setTimeout() or fetch()).
  • The API (not the callback) is what introduces the asynchronous behavior.

Callback Alternatives

Asynchronous callback solutions are difficult to write and difficult to debug.

Because of this, modern asynchronous JavaScript do not use callbacks.

Modern JavaScript offers superior alternatives for handling asynchronous operations, using Promises and the async/await syntax, which provide a cleaner flow and better error handling.


When to Use a Callback?

Callbacks are still important to understand.

Where callbacks really shine are in asynchronous functions, where one function has to wait for another function (like waiting for a file to load).


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

-->