omer'sinn

4 min read

Synchronous and Asynchronous Programming in Javascript

Javascript

Well, synchronous and asynchronous, we all heard about these terms when we just started learning programming. We've watched lots of videos and read lots of articles about it. Yep, that is also what I did, and now I also wanted to write an article about it.

Here is the simple definition of Javascript.

JavaScript is a single-threaded, non-blocking, asynchronous, concurrent programming language

What are all these terms here ? Well let's have a look.

What is synchronous and asynchronous

Synchronous programming happens when the execution of operations is done sequentially. An operation will only be executed after the previous one is done. (single thread) So, if a previous operation has an error, the other operations won't take place. This is also what we called the term 'blocking'. Because it just blocked other operations not to process.

On the other hand asynchronous programming does the operations at the same time. It doesn't wait for other operations to end. Next operation can occur while the previous operation is still getting processed. That is why we call it 'non-blocking' or 'multi thread'. Eventually 'asynchronous' and 'concurrent'.

Lets give a real life example from here:

Consider the preparation of a meal. When a person is alone preparing a meal, they will have to do all the tasks by themselves. And some steps require food processed in previous steps. You can rearrange the order slightly, but some steps have a fixed order. You can only mince a carrot after you’ve unpeeled it, for example.

However if adding another cook to the kitchen allows for more time efficiency. While one person is taking care of chopping vegetables, another can start making the sauce. By adding yet another cook, they can prepare the meat while the other two are working. And so on. There are still some steps that need to happen in sequence (the assembly of the dish after every ingredient is prepared is an obvious one), but others can be carried out independently to speed up the process.

So asynchronous programming can make the things work faster and simultaneously. But does this mean we should always use asynchronous programming. Well, no.

When to use synchronous or asynchronous programming?

Well let's take the example above and illustrate it with the picture below. The first part and second part show synchronous and asynchronous situations respectively.

As we can see, adding a second cooker to kitchen can make the process faster, but eventually we have to wait for dish to be served. If we add another cooker to serve the dish before chopping vegetables and making the sauce, the cooker would serve an empty plate. And we definitely don't want to serve an empty plate right :)

So, we can't serve the dish before it is ready. But chopping vegetables is independent from making the sauce. So we can make two cookers work at the same time for different tasks.

As a result, If we have independent tasks and don't need to follow a fixed sequence we can basically use asynchronous programming. However, if we need things to occur in a fixed sequence and have to wait for another tasks to end, we need to choose synchronous programming.

Now let's look at these terms in Javascript examples.

Javascript Examples

Well let's start with a really basic synchronous example.

console.log("First"); console.log("Second"); console.log("Third");

and the output will be:

First Second Third

It worked as it is expected. One and one after in a sequence. Tasks wait previous tasks to end. Sometimes, we don't want this. Because this is what we called 'blocking' and may cause some delays in user interface. That is when we want things to become asynchronous such as:

console.log('First'); setTimeout(() => console.log('Second'), 2000); console.log('Third');

and the output will be:

First Third Second

As we can see, third gets printed before second, because of the asynchronous execution of the code. setTimeout function waits for 2 seconds but in the meantime console.log('Third'); works. That means asynchronous execution doesn't block the upcoming tasks.

However there can be some cases where people may get confused such as:

let a = 1; let b = 2; setTimeout(() => { console.log("This is a:" + a); }, 2000); a = 10; console.log(b);

and the output will be:

2 This is a:10

Well, you could have expected to see a is still 1 but that is not how it works. And it doesn't change when you make 2000ms to 0ms because setTimeout is asynchronous and jumps to the rest of the code where a becomes 10 and eventually logs a as 10. We will look into this closer in the next blog where I will be talking about Event Loops.

Conclusion

Synchronous programming is a simple and default way of programming. Things don't get confused, each line is executed by order. This is why it is slower than asynchronous programming. Synchronous programming can also make other tasks to get blocked which may lead the entire page or project to shut down.

On the other hand, asynchronous programming works faster and it doesn't block other tasks. So the entire page/project doesn't need to be shut down if any errors occur in the meantime. However, code can get more complex and hard to understand. It should be designed well and handled properly.