Understanding JavaScript Runtime!

Shrushti Polekar
3 min readSep 14, 2020

--

JavaScript is a single-threaded programming language, as it has only one Call stack and memory heap. Well, this makes things pretty slow because if any other program wants to execute then that program has to wait until the previous program has completed being executed.

This is where JavaScript Runtime comes into the picture! While the synchronous JavaScript code is running, we have the web browser running in the background. We have something called Web API or web browser API which lets the JavaScript Engine know that there’s some work pending to be done in the background.

The web API comes with the browser. All Browsers along with JavaScript Engine have their own JavaScript Runtime that provides web API. These web APIs do a variety of things like sending HTTP requests, listening to events etc..For eg. go to the console and type window.The console will provide you with list of operations like setTimeout(),indexedDb(),setInterval() and many more…

These operations are called Web APIs and they are asynchronous! That means one can instruct these APIs to do something in the background and return the data once it is complete. Meanwhile, we can just continue working on the Call Stack and execute functions in it.

Let’s understand this in more detail!

Whenever the call stack encounters with something like setTimeout() or setInterval(), what it does is, it sends it to WebAPI.The WebAPI handles it (performs those operations in the background) and once it is done with it, it places that in the Call back Queue. Then the Event Loop checks whether the call stack is empty? If it is completely empty then only it places that function into the call stack. And then the call stack finally executes it!

Let us see an example

Consider the below code,

  1. First of all the console.log(‘1’) is placed onto the call Stack and it is been executed and then eventually removed from the call stack.
  2. The call stack then encounters setTimeout() , as soon as it encounters it, it sends it to the WebAPI to handle it.The Web API executes it in the background.
  3. Meanwhile console.log(‘3’) is placed onto the call Stack and gets executed.
  4. Then after 1000ms console.log(‘2) is placed onto the call back Queue and then the event loop checks whether the call Stack is empty by that time.If so, it then places setTimeout() onto the Call Stack and then call Stack executes it accordingly!The output that we get is it as follows..

To wind it up all, one most important thing is Node.js is a JavaScript Runtime. It was created in 2009 to execute JavaScript outside the browser since we had WebAPI, call back, event loop browser-based!

--

--

No responses yet