Skip to main content

Callback Functions

What is the callback function?

You would be hearing the term callback function a lot in JavaScript. Callback functions are functions that are passed as arguments to other functions, which is then invoked (called) inside the outer function to complete some kind of routine or action.

info

In JavaScript, functions are first-class objects, which means that they can be passed around as arguments to other functions, returned from other functions, and assigned to variables.

Example

Here is a simple example of a callback function in JavaScript:

Callback function
function greet(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}

function sayGoodbye() {
console.log("Goodbye!");
}

// Passing the sayGoodbye function as a callback to the greet function
greet("Rizwan", sayGoodbye);

In this example, the greet function accepts a name and a callback function as arguments. When the greet() function is called, it logs a greeting to the console and then executes the callback function. The sayGoodbye() function is passed as the callback function and is executed after the greeting is logged.

The output of this code would be:

Hello, Rizwan!
Goodbye!

You can also write functions inside the arguments of another function. In fact, this is the best practice. Here's an example of writing a function inside the arguments of another function:

Function inside the arguments of another function
function greet(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}

greet("Rizwan", function sayGoodbye() {
console.log("Goodbye!");
});

So, we don't have to write a separate function for the callback function. Just write the anonymous function inside the arguments of another function, and it will work just fine.

I prefer arrow functions for this purpose. Here's an example of writing an arrow function inside the arguments of another function:

Arrow function inside the arguments of another function
function greet(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}

greet("Rizwan", () => {
console.log("Goodbye!");
});

Usage

Callback functions are used in many places in JavaScript, such as:

Array Methods

Callbacks are used with array methods, such as forEach(), map(), and filter(), to perform a specific action on each element of an array.

Here's an example of using a callback with the forEach() method to double the value of each element in an array:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach((number) => console.log(number * 2));

// Output:
// 2
// 4
// 6
// 8
// 10

In this example, the callback function is an anonymous function function (number) {console.log(number * 2)} that takes a single argument, number, and console logs the value of number multiplied by 2.

Event Listeners

Here's an example of a callback function that logs a message to the console after a button is clicked:

Add a click event listener to a button
function sayHi() {
console.log("Hi");
}

const button = document.getElementById("myButton");
button.addEventListener("click", sayHi);

In this example, the sayHi() function is passed as a callback to the addEventListener() method, which is called when the button is clicked.

HTTP Requests

Here's an example of using a callback with the fetch() method to make an HTTP request:

fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((users) => console.log(users));

Here, the fetch() method is used to make an HTTP request to the JSONPlaceholder API. The fetch() method returns a Promise object, which is handled using the then() method. The then() method takes a callback function as an argument, which is executed when the Promise is resolved.

Timers

Here's an example of using a callback with the setTimeout() method to log a message to the console after 2 seconds:

setTimeout(() => console.log("Hello"), 2000);

In this example, the setTimeout() method is used to log a message to the console after 2 seconds. The setTimeout() method takes a callback function as an argument, which is executed after 2 seconds.

Promises

Here's an example of using a callback with the then() method to log a message to the console after a Promise is resolved:

const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Hello"), 2000);
});

promise.then((message) => console.log(message));

Callback Hell

When you have a lot of nested callbacks, it can be difficult to read and understand the code. This is called "callback hell" or "pyramid of doom".

Conclusion

In this article, we learned about callback functions and how to use them in JavaScript. We also learned about callback hell and how to avoid it.