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.
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:
- We passed it as an argument to the
showBestColor()
function - 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."
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:
- We passed it as an argument to the
setTimeout()
function - The
bestColor()
function got invoked insidesetTimeout()
function bestColor(color) { console.log("My best color is " + color + ".");}
setTimeout(bestColor, 3000, "White");
// The invocation above will return: "My best color is White."
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."
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.