Javascript — single threaded, non-blocking, asynchronous, concurrent language

Abhinav Rai
Sep 3, 2019 · 4 min read

Well, what? I use languages to get my job done. And for me and javascript this process started with building a small game, ajax requests and form validations. Our bond deepened with Hapi js. I’m committed to it since I came across React. Now, to become a better programmer you got to ask the whys of how things work. Javascript runtime has been one of the biggest mysteries for me.

What is Javascript engine and Runtime?

Javascript runtime refers to where your javascript code is executed when you run it. That said, javascript can be executed on google chrome, in which case your javascript engine is v8, if on mozilla — it is spidermonkey, if IE — then its chakra, if Safari — it’s nitro and if on node, again its v8. Now what is JS engine and what is JS runtime?

Engine converts the javascript we write into machine code. All JavaScript engines implement specification of the language provide by ECMAScript. Standardisation facilitates the development of independent engines and ensures your scripts give the same results no matter where you run them. In order to obtain speed, V8 translates JavaScript code into more efficient machine code instead of using an interpreter. It compiles JavaScript code into machine code at execution by implementing a JIT (Just-In-Time) compiler like a lot of modern JavaScript engines do such as SpiderMonkey or Rhino (Mozilla). The main difference here is that V8 doesn’t produce bytecode or any intermediate code. JavaScript engine is just a building block of a bigger concept. This engine works inside an environment called Javascript Runtime which provides additional features to our scripts. These features can be making a call to web, catching mouse/keyboard events, etc.

This is the architecture of a JS Runtime. V8 does not have these WebAPI’s. These are given by runtime. In chrome browser JS runtime, browser has it while in Node it’s given by C++ libraries.

Runtime Architecture

Let’s go with how is Javascript asynchronous and single threaded.

Single Threaded, What??

Javascript code is executed in a single thread but Javascript runtime is not run in single thread. Thread pool exists in JS runtime but we don’t have to worry about it as Runtime takes care of it. But how does it does that? Event loop to the rescue.

Lets understand what is Heap and Call stack in the Runtime (or in JS enginee which belongs to Runtime). The javascript code is first converted to machine code. Heap stores all the variables and call stack performs the operations.

console.log("Start")function sayHello(name) {
console.log(`Hello ${name}!`)
}
sayHello("Abhinav");console.log("End")

All these go to call stack and are executed there.

Start
Hello Abhinav
End

We can divide the scripts in 2 types namely — immediately invoked and invoked for later.

What happens when asynchronous tasks come? Tasks which take time to run. Say making an API call or Timer, etc. There is a concept called callback. It is the function to be executed when this task is done.

Well they go into the call stack as any normal functions but we make a call to WebAPIs as this task resided in WebAPIs. It stores the callback function for the task and does the task for us (using threading / multi processing depending on the runtime). And when the task is finished, it sends the callback to callback queue.

Visualise again here.

Now what is event loop? Event loop runs continuously (in Browser runtime which it doesn’t always runs in node) to check if the call stack is empty and if it is empty, it picks up the first item from the callback queue and moves it to call stack and executes the callback function. Until the stack is not empty, no function is added from callback queue.

Callbacks are A L W A Y S executed completely. The Event loop runs one callback at a time. No context switching. All callbacks in the queue have to wait until the current one is finished. If a script runs too long, it blocks others. That’s why callbacks should be relatively short and simple.

Pretty simple right! But in reality it’s much more complex. There are multiple queues depending on the runtime and their priorities are different. There is something as rendering queue. Whose job is to render the screen.

For any doubt in the basic model, watch this amazing video https://www.youtube.com/watch?v=8aGhZQkoFbQ. Let’s discuss Browser and Node Javascript runtimes in detail in the next blog. If you can’t wait, here is a great talk on the same — https://www.youtube.com/watch?v=u1kqx6AenYw&t=3s.

How is it non-blocking?

Say, when you make a call to an API and it fails or some other event is stuck, it’s still in the Web apis so it never goes to callback queue and hence call stack. So nothing is blocked.

Is it concurrent?

What is the difference between Concurrent and Parallel? Parallel is where you execute 2 tasks as the same time. (Watching movies while eating popcorn). This is achieved by multi-cores. JS code is executed concurrently and not parallely in the call stack. But WebAPIs can make use of multi-core and run parallely.

You can contact the author at abhinav.rai.1996@gmail.com

Abhinav Rai

Written by

Product Engineer at Go-Jek | Guitarist | Traveller | Entrepreneur

More From Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade