</> Code Corner

JavaScript · JS Async · Lesson 51

JS Callbacks

Functions passed as arguments.

A callback is a function passed as an argument to another function, to be called later.

Example

<p id="demo"></p>
<script>
function display(something) {
  document.getElementById("demo").innerHTML += something + "<br>";
}
function calculate(a, b, callback) {
  let sum = a + b;
  callback(sum);
}
calculate(5, 5, display);
setTimeout(function () { display("This appears after 1 second (callback for setTimeout)"); }, 1000);
display("This appears first");
</script>
Tip: Callbacks really shine in asynchronous code, where a function has to wait for something (a timer, a file, a server response).

Keep reading “JS Callbacks”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋