DEV Community

Muhammad Rizwan Ashiq
Muhammad Rizwan Ashiq

Posted on • Edited on

Callback Function

What is the callback function?

You will be hearing the term callback function shortly (CB) a lot in JavaScript. In JavaScript, functions are objects, and objects can be passed as arguments to functions. 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.

Example

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

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

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

greet("John", sayGoodbye);
Enter fullscreen mode Exit fullscreen mode

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, John!
Goodbye!
Enter fullscreen mode Exit fullscreen mode

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 greet(name, callback) {
    console.log(`Hello, ${name}!`);
    callback();
}

greet("John", function sayGoodbye() {
    console.log("Goodbye!");
});
Enter fullscreen mode Exit fullscreen mode

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:

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

greet("John", () => {
    console.log("Goodbye!");
});
Enter fullscreen mode Exit fullscreen mode

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));
// It's CB here 👉 (number) => console.log(number * 2)
// It'll print double of each element
Enter fullscreen mode Exit fullscreen mode

In this example, the callback function is an anonymous function (number) => console.log(number * 2) that takes a single argument, number, and console logs the value of number multiplied by 2. Output will look like this:

2
4
6
8
10
Enter fullscreen mode Exit fullscreen mode

Event Listeners

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

function sayHi() {
    console.log("Hi");
}

const button = document.getElementById("myButton");
button.addEventListener("click", sayHi);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)