Explained: Asynchronous JavaScript

What is Asynchronous JavaScript?

Its one of the most important topics within the language itself as it governs how we perform tasks which take some time to complete (e.g. Getting data from a database or API). In a very simplistic form, Asynchronous JavaScript is code that can start now and finish later.

JavaScript is a synchronous language which means it runs lines of code line by line. Take a look at the next block of code for example:


Line two cannot run before line one finishes and line three cannot run before line two finishes. Make sense?

Asynchronous JavaScript provides us with the ability to be able to have some code in the middle of other code but not be in the way and block it from running on time.

Take a look at the block of code below:

console.log('one'); console.log('two'); setTimeout(() => { console.log('callback function fired'); }, 2000) console.log('three'); console.log('four');


'callback function fired'

The output above shows us the order of the code executed. As we can see, the setTimeout function is an asynchronous function because it didn’t block the code and let the other lines of code execute and then came back to the function to display the message after two seconds.