skip to content
Dev Journal

Callback

/ 2 min read

A callback is a function passed into another function to be executed later. This may sound complex, but it’s quite simple. You’ve likely seen callbacks in action before, such as in event listeners.

Example of a Callback

Consider an event listener:

button.addEventListener("click", function () {
// do something
})

This can be rewritten using a callback function:

function callback () {
// do something
}
button.addEventListener("click", callback)

Why Use Callbacks?

Callbacks are useful for two main reasons:

  1. Easily Swap Code: Callbacks allow you to change the functionality without altering the overall structure.
  2. Prevent Blocking in Asynchronous Code: Callbacks help manage asynchronous tasks without blocking the main execution thread.

Asynchronous Code

Synchronous code runs sequentially, while asynchronous code does not. For example, an event listener is asynchronous because its callback executes only when the event occurs.

The Event Loop

JavaScript uses an event loop to manage asynchronous operations. It maintains a call stack (todo-list) and an event queue (waiting-list). When an asynchronous event occurs, the callback is added to the event queue and executed when the call stack is clear.

more infos, see on Philip Roberts at JSConf Talk

Creating Callbacks

To create a callback, define a function that accepts a callback as an argument and then execute the callback within it:

function callbackAcceptingFunction (callback) {
callback()
}
function callback () {
console.log('callback activated!')
}
callbackAcceptingFunction(callback) // callback activated!

The callback also can accept arguments:

function callbackAcceptingFunction (callback) {
callback("Hello", "World")
}
function callback (arg1, arg2) {
console.log(arg1) // Hello
console.log(arg2) // world
}
// When you pass a callback as a parameter, you pass only the reference, not the execution
callbackAcceptingFunction(callback)

Summary

  • A callback is a function passed to another function to be executed later.
  • Callbacks are useful for flexible code and managing asynchronous tasks.
  • JavaScript’s event loop handles asynchronous operations.
  • Creating a callback involves defining a function that accepts and executes another function.

No exercises are required for this lesson. The main takeaway is understanding what a callback is and how to use it.