Concept of Synchronous & Asynchronous Programming in JavaScript — Part 1
While doing
JS
, one of the concept that confuses many beginners to intermediate level developers isAsynchronous (‘Async’) programming
. As it’s one of the most common concept inJavaScript
, you need to have a strong understanding of it before diving intoJavaScript
.
So, based on my research and findings, I decided to come up with an article on the Concept of Synchronous & Asynchronous Programming in JavaScript
which is divided into 3 parts covering the following concepts respectively :
In this part, we will be discussing about the first point on the list — Basics of Synchronous and Asynchronous Programming in JavaScript
along with some interesting examples. I request you guys to practice the examples by yourselves as well for better understanding.
In general, Synchronous code can be defined as — “a bunch of statements in sequence.” i.e., each statement in the code is executed one after another from top to bottom until the last statement finishes the execution. Thus, each statement has to wait for the previous one to complete execution.
Let’s practice an example to visualize our statement:
let a = 30
let b = 50console.log(a)
console.log(b)
The codes are executed sequentially and we get the following output:
30
50
Let’s jump into another example using synchronous functions;
let a = function(){return 20}
let b = function(){return 30}console.log(a())
console.log(b())
If we run this block of code, we will get the following output:
20
30
What I wanna convey is no matter however complex the statement is, each statement will be executed from top to bottom i.e, sequentially
. The function will be executed, and then the return value will be assigned and finally the next line will be executed. The first method can have like more than 1000 of lines inside it but still it will take all the time to execute the statements inside it and then only the assignment will occur. And all before the next line is executed. That’s the concept of Synchronous Programming
and that’s what JavaScript
is doing most of the time.
But consider a situation where we need to fetch some data from the server that can take some time based on the internet connection or data size or any other dependency. We can’t just freeze the UI during that period of execution. It’s not an instantaneous thing. That’s where Asynchronous Programming jumps in.
Let’s look into an example using setTimeout()
which is a very basic example of Asynchronous Programming
:
let a = 4
let b = 3setTimeout(function() {
console.log("Async Task 1")
}, 100)console.log(a)setTimeout(function() {
console.log("Async Task 2")
}, 90)console.log(b)
The output to above block of code will be:
4
3
Async Task 2
Async Task 1
We can see that even though setTimeout()
comes before, it prints at the last. That’s because setTimeout()
takes 100ms to complete.
As an
Asynchronous
method, it’s executed after all the synchronous tasks are executed despite the positions of the code blocks. So the concept is, if we useAsynchronous Programming
to execute non instantaneous tasks, the following task won’t have to wait for the preceding task’s completion to execute.
In above example, even if we set the delay time to 0 ms
, we will notice a similar behavior since the Synchronous
tasks are always executed before the Asynchronous
tasks irrespective of the position. Following the completion of the Synchronous
tasks, Asynchronous
tasks are executed afterwards in an order respective to their execution time. If you notice the output, you can see that Async Task 2
is printed before Async Task 1
since the delay time of second setTimeout()
is less than that of the first one.
Note: I suggest everyone to run the above example altering the delay time and do some other tweaks to get a better understanding and a clear concept if you guys are still confused.
Based on what we discussed, one last thing that can be confusing is the use of variables while using any forms of
Asynchronous
function. During such cases, it’s mostly always better to pass the variables into thatAsynchronous
function other than relying on them from outside theAsynchronous
function as they could be changed by rest of the program before that specific function/block is executed.
Let’s do one last example to be clear on what I am trying to convey.
let a = 1
let b = 2setTimeout(function() {
console.log("Async Task a = ", a)
}, 10)a = 5 // change the value of a after setTimeout()console.log(a)
console.log(b)
If you run this block of code, we will get the following as the output:
5
2
Async Task a = 5
As you can see, even if a
is assigned to another value after the setTimeout()
, the output of setTimeout()
is Async Task a = 5
. This is because, as we discussed earlier, setTimeout()
being an Asynchronous
function by default, it’s executed after all other Synchronous
tasks are executed sequentially irrespective of the time we set. That is, even if we set the delay time to0ms
, we will observe the same behavior. So, the variable a is already set to 5
before the execution of setTimeout()
resulting in above output.
Finally, we can conclude that Asynchronous Programming
makes it easier to handle more than one thing at a time and makes it possible to express waiting for long-running actions without freezing the program during these actions.
This is it for now. Hope it made easier for you to understand the core concept. Any suggestions regarding this article are highly appreciated as this is my first article ever.
Next part of this article is about Callbacks and Promises that made Asynchronous Programming easier. Click here to go to the next part of this article: Part 2