How concurrency is handled in JavaScript?
We all know that JavaScript is a single-threaded language. But it is capable of handling concurrency using its asynchronous nature. Sounds little bit confusing right?
Don’t worry! There is no rocket science behind that. It is all about JavaScript’s asynchronous nature.
So what is this asynchronous nature? Well, asynchronous nature is, some of the operations in a program is not executing sequentially. That is what we known as asynchronous nature.
Now you may have a question that what kind of operations will be executed sequentially and what will not. Easy as pie, there are two main operations in a computer program while it is executing,
- CPU operations (Computational)
- I/O operations
The CPU operations are faster than the I/O operations. So that I/O operations are more time consuming. So this could affect to reduce the performance of the program . This is the place where asynchronous nature apply. All the CPU operations execute sequentially while the I/O operations execute non-sequentially. In other words this is non-blocking I/O (NIO). which means I/O operations are not blocking the CPU operations.
Now let’s think how these non-sequential operations are being handled by the JavaScript engine? Here comes the hero… That is the event loop. This event loop is more likely a thread pool. It is running behind the JavaScript’s engine. It handles all the I/O operations without a delay. This is how the concurrency happens in JavaScript. Now we are confident with the concepts and theories. To get a more clear picture of these concepts and theories, let’s take an example and figure it out.
focus on the following simple JavaScript code snippet,
In the line number five we can see an I/O operation which is fetching a value from a database and assigning it to variable called “value”. Now we know these I/O operations are time consuming. Interpreter will not wait there until it fetch the value from the db and assign it to the variable. That is the asynchronous nature of JavaScript or NIO. So it goes to the line number seven quickly. At the time when line number seven executes, if the “value” variable is null we won’t be able to get the expected output.
We can overcome this problem using Async/ Await. But this is not the time to talk about async/ await. This is all about understanding the asynchronous nature of JavaScript. In the next blog post I will explain everything about async/ await.
Now you know the science😎. A million thanks to checking out my article, leave a few claps👏🏼 and share to help your peers if you feel you have learned something.