Nothing is like it seems: Asynchronous in JavaScript
Tags: javascript, learning, code, beginners
Published: 2021-07-24 17:24:46

> In the following, you will understand [what](#what-happened) means asynchronous in JavaScript and [why](#why-is-asynchronous-important) it is important, using as an example a song from the [Ramones](https://www.youtube.com/watch?v=krokQtkvd9M)

JavaScript it’s a useful and amazing language. You can write tons of applications in different environments: backend, frontend, desktop, mobile... and all with the same language!! It all is possible because of [its characteristics](https://developer.mozilla.org/en-US/docs/Web/JavaScript) and [asynchronous](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous) is part of the reasons.

Asynchronous as a concept brings us a lot of pros, however it can be kind of tricky at the beginning, basically because sequences are different from what we could expect. What did I mean? Let's see the following code 

``` javascript
function hey() {
  console.log("hey");
}

function ho() {
  setTimeout(() => {
    console.log("ho");
  }, 0);
}

function lets() {
  console.log("lets");
}

function go() {
  setTimeout(() => {
    console.log("go");
  }, 0);
}

function song() {
  hey();
  ho();
  lets();
  go();
}

song();
```
## Explanation of code

In the past code, we had 4 methods, all prints something in the console. 2 of them have a [timeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) function inside of them but both wait  __0 milliseconds__, so it gives us the idea that they shouldn't stop any time

We should expect an output like this:

``` javascript
// hey 
// ho
// lets 
// go
```
But we got this:

``` javascript
// hey 
// lets 
// ho
// go
```

weird, right? let's try to find answers to that mystery

## What happened

Well, it’s important to know that JavaScript supports synchronous and asynchronous code. __Synchronous__ code is executed just after being read and __asynchronous__ is executed “later”, but in this case, later does not mean after now, it means at one point in the future that we don’t necessarily know when it will be. 

As we could suppose, in the past example we got both types of instructions. Synchronous in methods *hey* and *lets* and asynchronous in methods *ho* and *go*. 

``` javascript
// call order:
function song() {
  hey();    // synchronous
  ho();    // asynchronous
  lets(); // synchronous
  go();  // asynchronous
}

// execution order:
// hey 
// lets  
// ho
// go
```
Regarding that, it can be explained how a method (*ho* method for example) can be called before another one (*lets* method) but the last method to be called (*lets*) shows the results first anyway.

## Why is asynchronous important

The short answer is because JavaScript is single-thread. 

A more detailed answer should start with what is behind the fact of being "single-thread", which means that JavaScript has just one [call stack](https://developer.mozilla.org/en-US/docs/Glossary/Call_stack) and that at the same time can be understood as that it only can do “one thing at the time”. 

> Single-thread -> one call stack -> one thing at the time

In simple terms, we just can do one thing at a time and If the call stack is busy, our application will be busy. So, we want our call stack to be as less over busy as we can, but sometimes there are tasks that no matter what we want, will take their time to be executed (request to an external API for example) and that inevitably will block the stack until the task ends the execution. 

How does JavaScript solve that problem? There is a famous catchphrase that recommends “think outside the box” and in this case, JavaScript does it LITERALLY because it takes off the "slow" tasks from the stack and executes them in another place. 

So using asynchronous code JavaScript is able to avoid the overload of the call stack, thus by the execution of "slow" tasks out of the stack somewhere we can do more than one thing at a time.

For example, the I/O operations in [Node.js](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/) are offloads to the system kernel whenever possible, taking advantage that modern operating systems’ kernels are multi-threaded.

## Nothing is like it seems...

Nothing is like it seems, that’s right, but now we know that the execution order is different from what we expect because there are some methods that execute asynchronously. And they executed this way in order to keep the call stack the freest possible because there is only one and if it is busy, the performance of our app will be affected. 

On other hand, it's important to know that asynchronous code in JavaScript can be present in form of [*promises*](https://javascript.info/promise-basics) and [*callbacks*](http://callbackhell.com), and once they are resolved, they come back to the call stack pushed by the event loop. 


> *This is just a very small introduction to very important concepts from JavaScript. Understanding the functionality of the concepts helps us to face in a better way many situations we can have while developing JavaScript code. You can keep learning about those in the following links:*

> * https://youtu.be/8aGhZQkoFbQ
* https://youtu.be/SrNQS8J67zc