Callback Function
Tags: webdev, javascript, beginners, programming
Published: 2023-06-13 03:17:16

## 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:

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

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

greet("John", 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:

```console
Hello, John!
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:

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

greet("John", 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:

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

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

## Usage

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

- [Array methods (such as `forEach()`, `map()`, and `filter()`)](#array-methods)
- [Event listeners (such as click events)](#event-listeners)
- [HTTP requests (such as `fetch()`)](#http-requests)
- [Timers (`setTimeout`, `setInterval`)](#timers)
- [Promises (`then()`, `catch()`, `finally()`)](#promises)

### 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:

```js
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
```

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
```

### Event Listeners

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

```js
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:

```js
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](https://jsonplaceholder.typicode.com/). 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:

```js
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:

```js
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.