The JavaScript Engine and Its Working

Vishalbatra
The Startup
Published in
7 min readSep 28, 2020

As we all know JavaScript is a bit weird language when compared to other programming languages but also very much popular when it comes to web development as well as native app development. Today, we can say that JavaScript is the backbone of development, whether frontend or backend, JavaScript tops it all.

There are a lot of frameworks of JavaScript that are rolled out and are already thriving in the market like React.js , Vue.js , Backbone.js and many more, the list goes on and on. But, here is the mistake that most people do. Most people start learning these JavaScript frameworks directly with very basic knowledge of JavaScript but believe me it is going to be a mess in the long term. I will tell you why that is.

Take a moment to think how many years do these frameworks last in the current market?

A framework which was the most popular 10 years ago may be the least used now. Yes, so the answer is 8–10 years. So you learn a framework with very little knowledge of JavaScript and you are good to go for a decade at max. But, what after that? What when the technology changes and market starts shifting to new frameworks?

The answer is learn JavaScript. If you want to stand out for decades then I think one should start learning the base of those frameworks i.e. JavaScript, because frameworks may come and go but if you know the base of that then you can switch to any framework you want to with very much ease.

I am sure that now you understand the need to learn JavaScript. So, let’s discuss some of the basics of JavaScript.

What is JavaScript?

It is a single-threaded and synchronous language.

Happy with the above explanation?

A big NO, this is what you get after typing JavaScript in the Google search engine. These two big scary words that do not make sense even though they make a lot of sense.

You will be knowing what that means by the end of the article. Trust me by then.

So, coming to the big question, what single-threaded and synchronous means?

Answer: Execute one instruction at a time synchronously, not more than one.

But wait a minute, we all heard about asynchronous tasks in JavaScript like AJAX requests, then how does JavaScript handles these asynchronous tasks?

It may sound confusing at first but believe me, it’s not that messy.

I will explain the terminology first, then show you some examples for better understanding.

Syntax parser

It reads your code character by character and determines what it does and checks if the grammar is valid. You can think this of it as an interpreter which translates your code into machine-readable code.

Lexical environment

It simply means where your code physically sits in your program. The position of your code in the program will determine the lexical environment. I will tell you more about this with an example.

Execution Context

JavaScript runs your code in an execution context. Whenever we call function, a new execution context for that particular function is created and is put on the top of the execution stack.

In the execution context, we have three things initially:-

• Global object

• Special variable this (created by JavaScript engine)

• Outer reference

Let’s see an example:-

Execution stack of above example

When you run the above program:

• A global execution context is created and placed at the base of the execution stack site that is the very first thing that executes.

• Then foo() function is invoked and a new execution context is created and placed above the global execution context.

• Then bar() is invoked creating its own execution context and placing itself at the top of the stack. As soon as the function returns the value or we can say that the function has executed successfully, its execution context is immediately popped out of the stack and flow returns to the foo() context which was just below the bar() context.

But what is the output of the above program?

When you run this program in any other language it will give you an error of temp variable not defined in bar() function. But here it will give you the output as:-

How is that happening exactly? How can we get the value of a variable when is does not even exists.

So here comes the concept of scope chaining, outer reference, and lexical environment.

As I told you when a function ran its execution context is created and it has 3 things. One of them is the outer reference.

To understand this I want you to keep these things in mind.

1) Have a look at the code and see where the function bar() and foo() sits lexically, i.e., their physical position. Both functions are sitting globally which means they are not inside any function or object. So the outer reference of both the function is global.

2) In function bar() temp variable is not defined.

3) The global execution context has a variable temp with value 3.

4) The output is 3 and we will figure out why.

The bar function sits lexically in the outer environment as global. So when the program executes and the bar function is asked to console the variable temp on the screen, it starts looking for the variable in its scope. Upon not finding the variable within its own scope, instead of giving an error it will check that variable in its outer reference, which in this case is global and immediately get temp variable in the global execution context and there the value of temp is 3. It is called scope chaining.

If a function does not finds any variable within its scope, it looks for the variable in the outer reference and if that variable is available, the value is fetched.

Now, let us discuss a very confusing, yet the most asked and very important question in JavaScript.

How Asynchronous works in JavaScript?

Asynchronous: It simply means execute more than one instruction at a time. Sometimes a function takes a very long time to execute because of some http request or an input/output or a timeout request etc., it blocks and freezes the program for the meantime and the program comes to a halt. This is not what we want to happen as efficient coders. So here comes the concept of callbacks, promises, and async-await. I will discuss them in a separate blog but here I will show you an example that how the JavaScript engine handles these asynchronous tasks.

We already learned about execution stack and now it is time to discuss event queue and Web API. A Web API is a part of the JavaScript engine which handles the asynchronous tasks in the background and an event queue is full of events and notification of events that might be happening. These are responsible for handing the asynchronous requests.

Let’s take an example of a click event, what if we want to execute the function that is supposed to respond to a click or take the example of an HTTP request, what if we want to fetch data from somewhere while the program keeps running. Luckily, JavaScript provides a solution to all these problems. So all these time taking tasks are kept running in Web API provided by the JavaScript engine and when these tasks are completed it notifies the event queue that the task is completed. And the event queue waits for the execution stack to be empty. When the execution stack is empty and there is nothing more left to run in the program, the events in the queue start executing one by one.

So let’s understand with the above example:-

  • At the very first Global execution context is created and pushed into the stack.
  • foo() execution context is created and is put on the top of the stack i.e. above the global execution context, immediately the console command gets executed, the function is completed, so its context gets popped out of the stack.
  • bar() execution context is created and put on the top of the stack, the setTimeout function being a time taking process gets placed in the Web API of the JavaScript engine and kept running in the background not interfering or blocking the other code that is there and finally, its context gets popped out of the stack.
  • console command gets executed at a global level, printing text on the screen and global execution context gets popped out of the stack.
  • Now the execution stack is empty and it is time for the JavaScript engine to look the event queue and check if there is something to run. When the event was completed in Web API i.e. after 3 seconds (as you can see the setTimeout method), the event queue gets notified by Web API and the callback function of setTimeout gets run in its execution context, finally ending the program.

NOTE: As the name suggests event queue it will run in the order of FIFO i.e. whichever event will come first gets executed first. And the JavaScript engine will always run one event at a time so as said earlier JavaScript always works synchronously.

I hope this article was fun to read. Let me know your thoughts in the comment section and if you liked it, a few 👏 will definitely makes me smile.

--

--