Blog

Callbacks
Posted on September 22, 2020 in JavaScript by Matt Jennings

Definition

A callback is any function that is passed as an argument to another function, and then invoked from within that function.

More Callback Info

Using callbacks is very common in JavaScript and a lot of JavaScript libraries use callback.

Simple Callback Example

function print(number) {
  console.log(number);
}
const numbers = [1, 2, 3, 4];
/*
The "print" function that was declared above
is a callback because it was passed in as a parameter
to the numbers.forEach() method.

The "print" function will be invoked 4 tickets 
after it is passed into the numbers.forEach() method below.

The output below is:
1
2
3
4
*/
numbers.forEach(print);

Callback Example Where Code Runs Asynchronously

function func(callback) {
  setTimeout(() => callback(), 0);
}

/*
The output below in the Chrome browser is:
"Hello world!"
undefined
"This is a callback"

This is because the callback() function call
passed into the setTimeout() function is a callback
that is added to the message queue and message queue.
Since the console.log('Hello World!') method is placed on the 
call stack, and call stack items have priority over
message queue items, then the callstack item is executed
first then the message queue item which is:
func(() => console.log('This is a callback'));
*/
func(() => console.log('This is a callback'));
console.log('Hello world!');

 

Leave a Reply