bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

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.

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

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 !!";
}

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.

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

Runnable example

let result;
setTimeout(function() {
  result = 5;
}, 1000);
// What is result here?

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

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?

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

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

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

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);
});

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);
 });
 });
});

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

the next lesson explains what a Promise is.

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

JavaScript Promises

Previous

JavaScript Timeouts

Next

JavaScript Promises

This chapter

Overview
123

Lessons

539m

Read time

1. JavaScript Objects2. JavaScript Temporal Tutorial3. JavaScript Loops4. JavaScript Advanced Functions5. JavaScript Objects6. JavaScript Temporal Intro7. JavaScript Iterables8. JavaScript Function Definitions9. JavaScript Object Properties10. JavaScript Temporal vs Date11. JavaScript Iterators12. JavaScript Callbacks13. JavaScript Object Methods14. JavaScript Temporal Duration15. JavaScript Generators16. The JavaScript this Keyword17. JavaScript this Keyword18. JavaScript Temporal Instant19. JavaScript Function call()20. JavaScript Display Objects21. JavaScript PlainDateTime22. JavaScript Function apply()23. JavaScript Object Constructors24. JavaScript Temporal PlainDate25. JavaScript Function bind()26. JavaScript PlainYearMonth27. Self-Invoking Functions28. JavaScript PlainMonthDay29. JavaScript Closures30. JavaScript Temporal PlainTime31. JavaScript Objects - Advanced32. JavaScript ZonedDateTime33. JavaScript Object Definitions34. JavaScript Temporal Now35. this in JavaScript Objects36. JS Temporal Arithmetic37. JavaScript Object Iterations38. JS Temporal Differences39. JavaScript Object Accessors40. JS Temporal Compare41. JavaScript Object Management42. JavaScript Temporal Conversion43. JavaScript Object Protection44. Temporal Display Formats45. JavaScript Object Prototypes46. JavaScript Temporal Mistakes47. JavaScript Classes48. Migrate from Date to Temporal49. JavaScript Class Inheritance50. Temporal Standards51. JavaScript Static Methods52. Asynchronous JavaScript53. Asynchronous Programming54. JavaScript Timeouts55. JavaScript Callbacks56. JavaScript Promises57. JavaScript async and await58. JavaScript fetch API59. Debugging Async JavaScript60. JavaScript Modules61. JavaScript Modules Export62. JavaScript Modules Import63. JS Module Namespace64. JavaScript Dynamic Modules65. JavaScript Meta Programming66. JavaScript Reflect67. JavaScript Proxy68. JavaScript Typed Arrays69. Typed Array Methods70. JavaScript ArrayBuffer71. JavaScript DataView72. JavaScript Atomics73. JavaScript HTML DOM Navigation74. JavaScript HTML DOM Elements (Nodes)75. JavaScript HTML DOM Collections76. JavaScript HTML DOM Node Lists77. JavaScript Window - The Browser Object Model78. JavaScript Window Screen79. JavaScript Window Location80. JavaScript Window History81. JavaScript Window Navigator82. JavaScript Popup Boxes83. JavaScript Timing Events84. JavaScript Cookies85. Web APIs - Introduction86. JavaScript Fetch API87. Web Geolocation API88. Web History API89. Pointer Events API90. Web Storage API91. JavaScript Validation API92. Web Workers API93. AJAX Introduction94. AJAX - The XMLHttpRequest Object95. AJAX - XMLHttpRequest96. AJAX - Server Response97. AJAX XML Example98. AJAX PHP Example99. AJAX ASP Example100. AJAX Database Example101. XML Applications102. JavaScript JSON103. JSON Syntax104. JSON vs XML105. JSON Data Types106. JSON.parse()107. JSON.stringify()108. JSON Object Literals109. JSON Array Literals110. JSON PHP111. JSON HTML112. JSONP113. JavaScript / jQuery DOM Selectors114. JavaScript / jQuery HTML Elements115. JavaScript / jQuery CSS Styles116. JavaScript / jQuery HTML DOM117. JavaScript Graphics118. HTML Canvas119. Plotly.js120. Chart.js121. Google Chart122. D3.js123. JavaScript Interview Preparation

On this page

"I will call back later!"What is a Callback Function?Event HandlingAsynchronous OperationsThe Timing ProblemThe Callback IdeaSequence ControlCallback Error HandlingCallback DrawbacksCallback AlternativesWhen to Use a Callback?