working principle and underlying concept of javascript

How JavaScript Works? | Working of JavaScript engine

We all know the importance of javascript in web development. It is a one-man army type language which is ruling over the decades in the field of website development.

In several books, it is written that javascript is a client-side scripting language.

Client-Side means javascript runs in the client’s browser which is true but not completely true. Nowadays programmers are also using javascript on the server-side.

If you are following my articles, In some of my articles, I have shown my love for web development, like in this one. I talk too much and also practice web development a lot.

Every beginner who is learning javascript starts coding directly without understanding the fundamentals and working of javascript. When they go for an interview they are not able to answer some basic questions. I have also seen this problem with many experienced programmers.

Therefore, my goal from this article is to teach how javascript works and also the working of the javascript engine behind the scene.

You need to revisit this article many times in your life because it will take some time to grasp the concept. Therefore bookmark this for future reference.

Suppose that someone asks you the question of how javascript works? Now think about the answer to the question, if you somehow managed to answer the question.

Now he again bombarded with some more question like these:-

  1. Explain Synchronous vs Asynchronous JavaScript?
  2. JavaScript is a single-threaded language that can be non-blocking?

Oh boy, I am sure if you have only focused on the coding part then you might not know the answer to these questions? And if the interviewer asks such type of question then you will not able to answer.

But don’t worry because now you are my friend and In this article, I will cover all these questions.

So without wasting too much time let’s jump right into it.

What is a program?

Before learning the working of javascript, first, learn what is a program. Because this what you write and browser which contains javascript engine executes.

Program is simply a set of instructions that you write to perform a certain task.

E.g. you write javascript to validate the form, fetch data from external API when a user clicks the button, etc. All these things can be done by writing programs in javascript.

To execute the javascript code browser needs to do two things:-

  1. Allocate the memory to the program, and
  2. Parse and execute the code.

Every browser has a javascript engine that reads and executes the javascript and makes javascript works. Google Chrome ( the most popular used browser ) has a V8 engine that reads javascript and changes into machine-executable code.

Similarly, another browser has also its engine and runs javascript accordingly.

  • Firefox has SpiderMonkey
  • Safari has JavaScriptCore (also called Nitro)
  • Edge has Chakra

V8 engine or any other engine of javascript consists of two parts (i) Memory Heap, and (ii) Call Stack.

concept of how javascript works and image of javascript engine
JavaScript Engine

Now, it is good to learn about Memory Heap and Call Stack and how javascript works.

Memory Heap

const a = 1;

Read the above line of code, this is the very simple line of javascript I wrote for you to make the memory heap topic understandable.

Here, I assigned 1 to the variable name “a”, when this program will start executing in the browser, and as soon as the engine read this line memory allocation will happen in the memory heap.

Memory Heap is nothing but a block of memory that allocates the memory to your program to need the program to be run and it is limited in size.

Your program will contain some variable initialization steps like above and to save variables, the memory will be allocated in the memory heap.

Just for the sake of your information, if you are going to become a developer, you will hear the term memory leak, Well we all know that we have a limited amount of memory assigned to be work with a browser.

Memory Leak happens when there is some unused memory and you forget to remove them that usually happens when you assigned a variable as a global variable.

Now you have a basic understanding of memory heap, and it is a good time to learn the concept of the call stack. So, let’s jump into another section.

Call Stack

If you are coming from a technical, or let say coding background then I am assuming that you might know about stack data structure, and if not? Then don’t worry. I am here to help you.

A stack is a linear data structure that works on the principle of LIFO ( Last In First Out ) which means the element inserted last will be popped, delete, or processed first.

And the call stack in the javascript engine is also the stack data structure, which means it also works on the principle of LIFO.

JavaScript engine reads each line of js code and pushes the executable statement into the call stack.

Each statement is added to the call stack then the engine executes the statement and removes elements one by one from the top of the call stack after executing it.

E.g. 

const one = () => {
const two = () => {
console.log('4');
}
two():
}
one();

Let see the pictorial representation of the call stack of the above function and understand how the call stack of javascript works in visual form.

When the execution of code starts, the javascript engine sees the calling of function one() and adds it into the call stack, then the call stack will look like this.

JavaScript Call Stack 1

Since, only function “one()” is in the call stack its execution start, during the execution of the function one engine sees the other function “two()” and adds it into the call stack.

JavaScript Call Stack 2

Now “two()” is at the top, execution of two will start and see the console.log statement and further add it into the call stack.

JavaScript Call Stack 3

Now there is nothing to be added to the call stack, so the final execution of code starts.

In the call stack, the top of the stack is console.log(“4”) statement, it will be run first and remove from the stack then function “two()” will also be removed, and lastly function “one()” will be removed after execution.

This is how the calls stack works. You have understood the concept of Memory Heap and Call Stack completely.
It is the best time to answer some questions which were asked at the beginning of the article.

Single Threaded Working of JavaScript

Let’s revise the statement that I discussed with you at the beginning of the article i.e. JavaScript is a single-threaded language that can be non-blocking.

In this section, I will explain the meaning of single-threaded and in the next section I will discuss how javascript can be non-blocking.

Single-Threaded means one call stack and one call stack means javascript will do one thing at a time.

The Call Stack is First In Last Out or Last In First Out, It is similar to the stack data structure, I have already explained this in the above section.

Various programming languages like Java is a multithreaded language that means more than one call stack and it can do more than one task at a time.

You might be thinking why javascript developers have not designed javascript to be multithreaded because it seems that multithreaded is quite faster than single-threaded.

Yes, you are thinking right but working on code in a multithreaded environment can be very much complex sometimes, it can lead to deadlock.

You will be surprised to know that you just learned synchronous programming. Are you thinking about how? then read the next section.

Synchronous vs Asynchronous Programming

Synchronous programming simply means run one line of code at a time and wait for the duration of execution of that line of code and after the execution run another line.

There are many hard words used for defining synchronous programming but I don’t want to confuse you with that bookish word, if you can understand the above statement then you are good to go.

Suppose some piece of code is taking too long to give a result then it will not move to the next line to execute the code.

Now you can imagine with synchronous programming if you have to run three statements and the second one is the massive one which is going to take lots of time then the javascript engine will not execute the next line and it will block the browser then your client will not able to interact effectively with the site.

Here the question arises, Is there any method by which I can make javascript non-blocking?

And the answer is YES! Asynchronous programming is the solution to this problem.

E.g. 1

console.log('1');
console.log('2');
console.log('3');

The above code is implementing Synchronous programming.

E.g. 2

console.log('1');
setTimeout(()=>{
console.log('2');
},2000);
console.log('3');

The above code is implementing Asynchronous programming.

Wow, you just skipped the second line and implement the asynchronous programming. In order to understand it completely let’s read the next part of this article.

JavaScript Run-Time Environment

JavaScript Run Time Environment

JavaScript needs a memory heap and call stack to run the program. But Javascript needs more than just the engine. And we call it a JavaScript Run-Time Environment.

JS run-time environment has more than just the engine. It includes Web APIs, Call Back Queue, and Event loop also.

As you can see setTimeout is part of the Web APIs, therefore you can do asynchronous programming.

Now again let us see the working of example 2.

  1. Firstly, the console.log(‘1’) statement will be added into the call stack, then run, and remove from the stack.
  2. Then it sees the setTimeout() function, again it is added into the call stack, since, it is not the part of javascript directly and it is a part of web API which comes with the browser. It is removed from the stack and triggers the WEb APIs part and will be run after the given time interval. In our case, it is 2000ms ( 2 sec ).
  3. Since The call stack is still empty, then the next statement console.log(‘3’) will be added into the stack, run, and remove from the stack.
  4. After the 2 sec, the web API is going to say, hey, I have console.log(‘2’) in setTimeout. setTimeout is done and we have a call back of setTimeout, and it will be added into the call back queue.
  5. Finally, Event Loop will come into the role. The event loop checks every time the call stack is empty or not. If the call stack is found empty as in our case it is empty then it checks the callback queue because if the call stack is empty then it pushes the code from the call back queue to the call stack and makes the js engine work. In our case, console.log(‘2’) will be inserted into the call stack, run, and popped out from the call stack.

This is the overall working of the JavaScript run-time environment.

Conclusion

In this one single article, I have covered all the questions which I asked from you at the beginning of the article and these are:-

  1. How does JavaScript work in the browser?
  2. Explain the working of the JavaScript engine?
  3. Explain synchronous vs asynchronous javascript? And
  4. JavaScript is a single-threaded language that can be non-blocking?

These questions are very important because the interviewer can ask these tricky questions. So next time must prepare yourself.

When you write javascript code underneath the hood, it goes through various stages. JavaScript engines like V8, Web APIs, Callback Queue, and Event loop all work together to make java script run in the browser.

This is how javascript works behind the scene. I hope I was able to make all points clear with the text and visuals.

This is a very important concept in javascript because it builds a basic foundation about how javascript works in the browser.

I can understand this concept is not simple to understand in the first time reading but If you have understood it then well and good, but not, then please bookmark this article for your future reference and revisit it when you need.

Thank you for reading this article and spending your precious amount of time learning it. I am happy today because you have built the basic foundation of javascript now and you are ready to learn some advanced topics.

Please share this article if you think it will add some value to other’s life because sharing is caring.

Also Read:-

Leave a Comment

Your email address will not be published. Required fields are marked *