Synchronous vs Asynchronous Javascript

Divyansh Mahajan
Innovaccer Design
Published in
5 min readSep 2, 2018

Introduction

Javascript could take a toll if not implemented correctly. Having said that, Javascript is one of the most growing programming language because of so many libraries being available in the ecosystem to solve almost all your frontend or backend problems.

Frontend frameworks like React, Angular, Vue have changed the way people look at frontend applications, it’s not just about writing HTML and CSS anymore. NodeJS on the other hand is being picked up by market leaders (Netflix, Uber, Paypal, Medium, etc) on the servers, to reduce I/O latency, because of it’s asynchronous nature.

What to expect?

I will try to explain the basic difference between Synchronous and Asynchronous programming using callbacks. Don’t worry even if you are new to Javascript, you’ll follow.

Asynchronous?

Talking about asynchronous nature of Javascript, makes everyone question, “What exactly does asynchronous programming mean?” Before understanding what is asynchronous programming, let us take a look at the following example.

Here we have a function getUserById, which takes a parameter “id”. It queries database, corresponding to the id and returns user details. Now let’s look at the output when this piece of code is executed.

The output of the program is as we may have expected. Pretty straight forward, right? The function getUserById executes with the user id 1, and it queries the database to return the result. Now, querying a database is a I/O operation and these typically take some time. Javascript is single threaded, which means it performs one operation at a time. Once our I/O operation is completed, let’s say it took 3 seconds to get response from the database, console statement prints User1's data on the screen. console.log is a simple Javascript command to print the data, and it doesn’t take much time to execute. Next we try to query database for User2’s data, and it takes another 3 seconds to get this data. Now, we have User2’s data printed on the screen. Within few milliseconds our last console statement is executed, letting us know that sum of 4 and 5 is 9. This entire program took almost 6 seconds to execute.

Clearly, Javascript callstack waits for one line to complete execution, and then proceeds to next line. This is called Synchronous or Blocking code. Now, let us consider the following example to understand Asynchronous programming.

This is the same program, written in a new way. The function we now use is getUserAsyncById and it also takes the same parameter “id”. In addition, it takes another parameter which is itself a function. This second parameter is called a callback.

Callback is a functionality of Javascript, which points the program to a function that will be executed once the result of the original function is ready. In our case, the callback will be executed, once getUserAsyncById completes the I/O operation and returns user data. Let’s look at the output now and see how is it different from the previous example.

Hunhh, what happened here?

The output here is not something we had expected. What happens here is, that when getUserAsyncById is executed, it knows that a callback function has been passed to it, so it doesn’t block the Javascript thread and wait for the I/O operation to complete. Instead, it moves to the next operation, and it calls getUserAsyncById function again to get data for User2, and similarly the thread continues and not wait for the response. Thread now moves to print the sum of 4 and 5, which is 9. After a moment, we see that data for User1 is printed on the screen, followed by User2's data being printed on the screen. Still unclear? Let’s understand what’s happening in the background.

When getUserAsyncById is executed for the first time, it moves out of the callstack and pushes the I/O operation to the event loop (We’ll talk about callstack and event loop a little later). Now, continuing getUserAsyncById is called again for User2, and similarly this also moves out of the callstack and pushes the I/O operation to event loop. Next command which is calculating the sum is not dependant on User1 or User2, hence it completes execution and prints the result “9” on the screen. After a while (dashed area in the image), User1 I/O operation is ready with the result, and now the callback must be executed. Callback for User1 executes, which prints the user data on the screen. Similarly User2 data is printed, when I/O operation is completed.

Note: User1 I/O and User2 I/O operation still take 3 second each, but User2 I/O operation didn’t have to wait for User1 I/O operation to complete, like in the previous example.

Though the functions individually took the same time to execute, but still the total time to execute the program is almost 3 seconds, which is 50% of 6 seconds in the previous example. This is because User2 didn’t wait for User1 to complete. Amazed? Well, say hello to Asynchronous or Non-blocking code.

This is pretty much the difference between Synchronous and Asynchronous programming. Callstack and Event loop are a little complex to understand, for now let’s consider that callstack contains everything that is to be executed and event loop is the list of all the callbacks to be executed.

Only Javascript allows Asynchronous programming?

The answer is “Not really!” We can achieve similar parallel processing by spawning multiple threads in other languages. But, it comes with the cost of increase in CPU and RAM utilisation. Javascript, on the other hand was built ground up to support Asynchronous programming.

Conclusion

Hope, this makes some sense and helps understand the difference between Synchronous and Asynchronous programming.

Asynchronous programming is something which makes Javascript outstand, and stronger than other programming languages. Learning Javascript could be a little tough, especially due to ecosystem changing so rapidly. It gets difficult to catch up with all the tools that help build awesome Javascript applications. But even though it may seem like re-inventing the wheel, JavaScript’s evolution has helped push innovations such as hot reloading, real-time linting, and time-travel debugging. Hope this article helps you understand the power of Javascript and motivates you to pick up Javascript.

--

--

Divyansh Mahajan
Innovaccer Design

Javascript enthusiast, love talking about performance for both Web and Mobile.