CALLBACK FUNCTIONS
Tags: javascript, beginners, webdev, codenewbie
Published: 2020-02-26 14:59:08

# What is a callback function? 🤔

As you might already know in javascript we can pass functions as arguments to another function.
 ✔️ will explain why you would want that later in this post.
 
> So, yeah a callback function is a function that is passed as an argument to another function [which is called a higher order function] to be called back at a later time.

Let's see an example 😃

```javascript

function Higher_Order_function(function(){
		setTimeout(function(){
			console.log('Served!');
		}, 2000);
	}
}

```

As you can see, here we are calling a function called `Higher_Order_function` and expecting it to log `Served` after 2s ⌛.

It is important to know that javascript is **Single Threaded.** and **synchronous [on the barebones].** That means it's not going to stop running for anything.

> We can use ajax , callbacks , async + await , promises to write asynchronous javascript code.

## Let's dig deeper ⛏️

Let's learn a few things on how javascript handles code so that we can dig a little deeper into how callbacks work.

✔️ CALL STACK
✔️ WEB API
✔️ CALLBACK QUEUE

Whenever javascript needs to excecute a function or a statement, it puts it into the **call stack.** After calling the function, it decides based upon the function wether it's a web api and if there is something which needs to be queued (**callback queue**) [remember javascript is single threaded].
Web apis just means that it needs to be handled asynchronously because we are not sure when we might receive the information needed from the api
ex: an external api, event loop , or basically anything we need to wait for.

Thanks to PHILIP ROBERTS for the visualization tool. You can see that in action [by visiting this link.](http://latentflip.com/loupe/?code=Cgpjb25zb2xlLmxvZygnUHJlcHBpbmcnKTsKCnNldFRpbWVvdXQoZnVuY3Rpb24oKXsKICAgIGNvbnNvbGUubG9nKCdzZXJ2ZWQhIScpOwp9LCAyMDAwKTsKCmNvbnNvbGUubG9nKCdjb29raW5nIScpOw%3D%3D!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D) 🔰


## Why use callback functions?

The idea here is to **queue** up the tasks which are currently waiting for something else to be resolved [Say, response from an external api] so that the **Call Stack** is free for the normal tasks to run. So, callbacks are useful for writing some asynchronous code when needed.

But it's not all butterflies and sunshine!

Have you ever heard of **Callback Hell**?

Well, the name is no mistake. There is an entire website dedicated to it http://callbackhell.com/ ℹ️.

It basically is a conundrum where we end up writing some asynchronous code using callbacks but chained and entagled to each other which makes it difficult for us to debug or even understand what's happening. 
Huh! feels like hell 😨

Let's see that with an example:

``` javascript

getData(function(x){
    getMoreData(x, function(y){
        getMoreData(y, function(z){ 
            ...
        });
    });
});

```

More on this here:

{% stackoverflow 25098066 %}

## Some interesting things worth learning 📗

**Should i be using callbacks? 😕** 

Well, as long as you understand what you are working with, you are good to use it. But if any other incremental changes may have to be done to that function then you are better off with promises.

I still use callbacks sometimes especially when i need a function like setTimeout. But other than that i always use promises and/or Rxjs.

**Why do i use promises or Rxjs instead of callbacks? 💭**

Well as you know callback functions are .... functions! that means they do not return a value themselves but will call a function at later point in time which returns a value.
But promises return value as soon as they are resolved or rejected. 
Same way with Rxjs Observables, it returns an observable which we subscribe to and then will return a value when the asynchronous task finishes.

**Note:** _An advantage of using Observables is that unlike promises we can emit multiple values over time using Observables, we can cancel if we choose to and can use with map, filter, reduce etc...with ease._

While there are many asynchronous tasks we can make use of promises in, I personally do a lot of _API calls_ and that is where i use promises and Observables [For caching and stuff] where previously when i was just using ajax or jQuery with callbacks, it was a nightmare to chain multiple requests and merge them to return the result [Rxjs just makes it easier].

Let's see that with a simple example:


**Using ajax and callback:**

```javascript

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

```

The above code, on success will run the function `handleData` which can have the logic you need.

**Using promises:**

```javascript

const baseUrl = `https://placeholder.com/`;

function callPlaceholder(){
	return this.http.get(baseUrl).toPromise();
}

```
And then use `then()` with callPlaceholder() as below:

```javascript

callPlaceholder().then( res => {
		console.log(res);
	},
	error => {
		console.log(error);
	}
)

```

So, yeah since we now have many ways to handle asynchronous requests, it's better to use them: [Especially for http requests]

✔️ XMLHTTPRequest.onreadystatechange()
✔️ jQuery methods
✔️ fetchApi
✔️ Axios
✔️ httpClients for respective frameworks & Rxjs🔥

For more info [visit this link](https://www.freecodecamp.org/news/here-is-the-most-popular-ways-to-make-an-http-request-in-javascript-954ce8c95aaa/)


**If you are curious about why javascript isn't multithreaded 👇**

{% stackoverflow 39879 %}


## Wrapping up 

We now know:

✅ what callback functions are
✅ how to use them
✅ why we use them
✅ the concept behind why we might need them
✅ and when to use them.


Hope this article has helped you! 💁‍♂️

Stay tuned 🍿 for the final post in this series `Generator functions`.

Thank you!😀