In JavaScript, functions can be treated like any other variable. So, it can be passed into a function and returned from a function.
A callback function is a function passed into another function as an argument.
Let's look at an example.
// callback function
const double = x => x * 2
// callback function
const half = x => x / 2
const arr = [1, 2, 3]
console.log(arr.map(double)) // prints [ 2, 4, 6 ]
console.log(arr.map(half)) // prints [ 0.5, 1, 1.5 ]
This example is a synchronous callback, and it allows us to keep the DRY principle.
Callbacks are often used to continue execution after an asynchronous execution.
An example of asynchronous callback is event handlers. Event handlers are a function that will be called on an event, not right away.
<div id="container">
<h1 id="id">not modified</h1>
</div>
// Function to change contents of h1
function toggleModify() {
const el = document.getElementById("id");
if (el.firstChild.nodeValue === "not modified") {
el.firstChild.nodeValue = "modified"
}
else {
el.firstChild.nodeValue = "not modified"
}
}
// Add event listener to
const el = document.getElementById("container");
el.addEventListener("click", toggleModify, false);
Oftentimes, callbacks become nested and they are difficult to understand and maintain. To avoid this problem, we can use a promise. A promise allows us to attach callbacks and do more than just a callback.
Callback functions also form closures, since it has references to its surrounding state!