Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# 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

Basic JavaScript

JS Tutorial JS Introduction JS Where To JS Output

JS Syntax

JS Syntax JS Statements JS Comments JS Variables JS Let JS Const JS Types

JS Operators

JS Operators JS Arithmetic JS Assignment JS Comparisons JS Conditional JS If JS If Else JS Ternary JS Switch JS Booleans JS Logical

JS Loops

JS Loops JS Loop for JS Loop while JS Break JS Continue JS Control Flow

JS Strings

JS Strings JS String Templates JS String Methods JS String Search JS String Reference

JS Numbers

JS Numbers JS Number Methods JS Number Properties JS Number Reference JS Bitwise JS BigInt

JS Functions

Function Path Function Intro Function Invocation Function Parameters Function Returns Function Arguments Function Expressions Function Arrow Function Quiz

JS Objects

Object Path Object Intro Object Properties Object Methods Object this Object Display Object Constructors

JS Scope

JS Scope JS Code Blocks JS Hoisting JS Strict Mode

JS Dates

JS Dates JS Date Formats JS Date Get JS Date Set JS Date Methods

JS Arrays

JS Arrays JS Array Methods JS Array Search JS Array Sort JS Array Iterations JS Array Reference JS Array Const

JS Sets

JS Sets JS Set Methods JS Set Logic JS Set WeakSet JS Set Reference

JS Maps

JS Maps JS Map Methods JS Map WeakMap JS Map Reference

JS Iterations

JS Loops JS Iterables JS Iterators JS Generators

JS Math

JS Math JS Math Reference JS Math Random

JS RexExp

JS RegExp JS RegExp Flags JS RegExp Classes JS RegExp Metachars JS RegExp Assertions JS RegExp Quantifiers JS RegExp Patterns JS RegExp Objects JS RegExp Methods

JS Data Types

JS Destructuring JS Data Types JS Primitive Data JS Object Types JS typeof JS toString JS Type Conversion

JS Errors

JS Errors Intro JS Errors Silent JS Error Statements JS Error Object

JS Debugging

Debugging Intro Debugging Console Debugging Breakpoints Debugging Errors Debugging Async Debugging Reference

JS Conventions

JS Style Guide JS Best Practices JS Mistakes JS Performance

JS References

JS Statements JS Reserved Keywords JS Operators JS Precedence

JS Versions

JS 2026 JS 2025 JS 2024 JS 2023 JS 2022 JS 2021 JS 2020 JS 2019 JS 2018 JS 2017 JS 2016 JS Versions JS 2015 (ES6) JS 2009 (ES5) JS 1999 (ES3) JS IE / Edge JS History

JS HTML

JS HTML DOM JS Events JS Projects New

JS Advanced

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


JavaScript Callbacks

"I will call back later!"

A callback is a function that runs later.

A callback runs after something has finished.

The name "callback" stems from the idea that the function will "call you back" later when it has finished its task.

Note

Callbacks were the first JavaScript solution for handeling asynchronous results that could not be available immediately.

This page explains what callbacks are and why they can cause some problems.


What is a Callback Function?

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

The callback function is intended to be executed later, typically when a specific event occurs or an asynchronous operation completes.

This pattern keeps your function flexible.

This is how many older JavaScript APIs worked.


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".


Asynchronous Operations

Windows functions like setTimeout() use callbacks to execute code after a specified delay.

Example

setTimeout(myFunction, 3000);

function myFunction() {
  document.getElementById("demo").innerHTML = "I love You !!";
}

Try it Yourself »

In the example above, myFunction is a callback function passed as an argument to setTimeout().

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

Note

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

Right: setTimeout(myFunction, 3000)

Wrong: setTimeout(myFunction(), 3000)


The Timing Problem

Asynchronous code finishes later.

This means you cannot return the result right away (before they are finished).

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.

Note

You cannot solve this problem by waiting in JavaScript.

Waiting would freeze the page.


The Callback Idea

The solution to the problem above, is to run the code after the result is ready.

You must give JavaScript a callback function to call later.

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.


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 Error Handling

Async code can fail.

Callbacks often use an error-first pattern:.

Examples

function getData(callback) {
  let ok = true;

  if (ok) {
    callback(null, "Data");
  } else {
    callback("Something failed", null);
  }
}

getData(function(error, data) {
  if (error) {
    myDisplayer(error);
    return;
  }
  myDisplayer(data);
});

Try it Yourself »

function getData(callback) {
  let ok = false;

  if (ok) {
    callback(null, "Data");
  } else {
    callback("Something failed", null);
  }
}

getData(function(error, data) {
  if (error) {
    myDisplayer(error);
    return;
  }
  myDisplayer(data);
});

Try it Yourself »

In the example above, the getData function is called with a callback.

The callback function has two parameters.

The first parameter is the error, and the second parameter is the result.

This pattern is common in older JavaScript code.


Callback Drawbacks

While essential for JavaScript programming, deeply nested callbacks can lead to complex, hard-to-read code known as "callback hell" or the "pyramid of doom".

Example

step1(function(r1) {
  step2(r1, function(r2) {
    step3(r2, function(r3) {
      console.log(r3);
    });
  });
});

Note

When callbacks get deep, debugging becomes difficult.

The logic moves from left to right and becomes difficult to follow.


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).


Next Chapter

The next page explains what a Promise is.

You will learn how promises can replace deep callbacks with a cleaner flow.

JavaScript Promises


×

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.

-->