What is a Callback Function?

Richard Chea
1 min readNov 25, 2020

--

A callback function is a function that is passed into another function as an argument, which is then invoked inside the outer function.

Let’s take a look at the print() function below.

function print(whoAmI) {
whoAmI()
}

The print function takes a parameter called whoAmI, which is a function, and calls it inside. The whoAmI function is a callback function.

Let’s take a look at another example.

const message = function () {
console.log("message with 3 second delay")
}
setTimeout(message, 3000)//can also be written in ES6 with arrow functionsetTimeout(() => {
console.log("message with 3 second delay")
}, 3000)

This setTimeout method will run the message function after 3 seconds have passed.

Callbacks make sure that a function is only going to run after the task has been completed. This helps us work with data in an asynchronous environment. For example, we’re required to fetch data and display it on the DOM. Callback functions can be used to help display the data to do the dom, only after it has completed the fetch and has retrieved the data.

--

--