Skip to main content

Callback – Definition, Meaning, & Examples of Callback Functions

A callback is a function A passed as an argument into a function B and invoked inside function B. In other words, after passing function A into function B, we expect function B to call back (invoke) function A at a given time.

note
  • Callback functions are sometimes called call-after functions.
  • The specific time function B will call back function A may be immediately or later in the future.
  • If the callback's execution happens immediately, the call-after is called a synchronous callback.
  • If the callback's invocation occurs in the future, the call-after is called an asynchronous callback.

Let's look at some examples of synchronous and asynchronous callback functions.

Example 1: Synchronous callback function in JavaScript

In the snippet below, bestColor() is a callback function because:

  1. We passed it as an argument to the showBestColor() function
  2. We invoked it inside showBestColor()
function bestColor(color) {
console.log("My best color is " + color + ".");
}

function showBestColor(callback, choice) {
callback(choice);
}

showBestColor(bestColor, "White");

// The invocation above will return: "My best color is White."

Try Editing It

The bestColor() callback function above is synchronous because we programmed its execution to happen immediately.

Let's now see an example of an asynchronous callback function.

Example 2: Asynchronous callback function in JavaScript

In the snippet below, bestColor() is a callback function because:

  1. We passed it as an argument to the setTimeout() function
  2. The bestColor() function got invoked inside setTimeout()
function bestColor(color) {
console.log("My best color is " + color + ".");
}

setTimeout(bestColor, 3000, "White");

// The invocation above will return: "My best color is White."

Try Editing It

The bestColor() callback is asynchronous because we programmed its execution to happen at a given time—after 3000 milliseconds (3 seconds).

An alternate way to write the code above is like so:

setTimeout(
function (color) {
console.log("My best color is " + color + ".");
},
3000,
"White"
);

// The invocation above will return: "My best color is White."

Try Editing It

The snippet above passed a complete function—not a reference—as a callback argument to the setTimeout() method. We also implemented the "inversion of control (IoC)" programming principle.

Join CodeSweetly's Substack