If you've been learning JavaScript you've probably heard the word callback thrown around. It sounds scary but by the end of this article it'll feel like second nature. Let's break it down.
Callback Function
A callback function is a function passed into another function as an argument, which is then executed or ("called back") at a later point in time to complete a specific task.
Types of Callback Functions
Asynchronous callbacks are executed at a later time, allowing the main program to continue running without waiting. This is essential for preventing the application from freezing during long-running tasks like network requests.
Synchronous callbacks are executed immediately within the outer function, blocking further operations until completion. Array methods like map(), filter(), and forEach() use synchronous callbacks.
Passing a Function as an Argument
function greetings(name, sayHi) {
return name + sayHi(); // call sayHi as a function with ()
}
function sayHi() {
return " Bonjour!";
}
console.log(greetings("Marie", sayHi)); // pass sayHi without () as the callback
// "Marie Bonjour!"
💡
sayHiis a callback function passed as an argument togreetings(), which then calls it internally to return the greeting alongside the name.
Event Handling
User interactions, such as button clicks or key presses, can be handled by providing a callback function to an event listener:
<!-- index.html -->
<button id="myButton">Click Me!</button>
// script.js
const button = document.getElementById("myButton");
button.addEventListener("click", clickedBtn);
function clickedBtn() {
alert("Button clicked!");
}
💡 In the example above, we first grab the button from the HTML, tell it to listen for a click via
addEventListener(), pass inclickedBtnas a callback without parentheses so we're not calling it ourselves, and finally let the browser call it for us the moment the click happens.
setTimeout()
Window functions like setTimeout() use callbacks to execute code after a specified delay.
<!-- index.html -->
<div id="display"></div>
const displayDiv = document.getElementById("display");
setTimeout(myFunction, 3000);
function myFunction() {
displayDiv.innerHTML = "I miss you!";
}
💡 In the example above,
myFunctionis a callback function passed as an argument tosetTimeout(), which waits 3 seconds before calling it to display the message inside thediv.
Array Methods
Many built-in array methods like map(), filter(), and forEach() accept callback functions to define the action performed on each element.
forEach() — loops through every element:
const fruits = ["apple", "banana", "mango"];
fruits.forEach(function(fruit) {
console.log(fruit);
});
// apple
// banana
// mango
map() — transforms every element into something new:
const numbers = [1, 2, 3];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // [2, 4, 6]
filter() — keeps only elements that pass a condition:
const ages = [10, 18, 25, 12, 30];
const adults = ages.filter(function(age) {
return age >= 18;
});
console.log(adults); // [18, 25, 30]
💡 In each example above, the anonymous function passed into
forEach(),map(), andfilter()is a callback — the array method calls it automatically on every element so you don't have to write a loop yourself.
Callbacks are everywhere in JavaScript. Once you recognise the pattern — a function passed into another function — you'll start seeing them in every codebase you touch.
Happy Coding!! ☺️
Top comments (0)