How does JavaScript work? đ€
Ganesh Jaiwal
Posted on October 20, 2020
Did you know the simple statement of JavaScript needs a lot of work done behind the seen to get it executed?
HmmâŠ
So the browser doesnât understand javascript directly.
Then how are we going to ask the browser to do something?
Letâs start with what language the browser understands.
The browser only understands 0s and 1s language i.e. Statements in Binary/Bits format.
We canât convert our whole JavaScript into bits easily. So what should we do now? đ€
JavaScript engine:- âHey donât worry I can help you with that give me your JavaScript fileâ.
What is a JavaScript engine then?
When a JavaScript file is loaded into the browser, JavaScript Engine executes that file line by line from top to bottom (Async code will be the exception, we will see async later in this series).
JavaScript Engine will parse the code line by line and convert that code into the machine code (Binary/Bits format).
Now browser can understand this machine code and behave accordingly.
Here are some JS engine examples.
Correction:-
With the Edge 79 release, Microsoft is switching to a Blink browser engine with a V8 JavaScript engine.
Both Blink and V8 are developed under Chromiumâan open-source project with an open-source web browser of the same name. Chromiumâthe open-source browserâis used by Google for its own Chrome browser. Now, Microsoft's Chromium Edge will do the same.
So what is inside this javascript engine?
Here is a very basic view of JavaScript Engine.
Memory heap
JavaScript engine is sometimes unable to allocate memory at compile-time, so variables that allocated at runtime go into memory heap (unstructured region of memory).
Data/Objects that we allocate in the heap section exist even after we exit the function which allocated the memory inside the heap.
Here we face a major problem of memory leak.
So what is a memory leak?
A memory heap has limited space.
If we keep using heap space without caring about freeing up unused memory. This causes a memory leak issue when there is no more memory available inside the heap.
To fix this issue javascript engine introduced a Garbage collector.
What is a Garbage collector?
Garbage collection is a form of memory management. Itâs like a collector which attempts to release the memory occupied by objects that are no longer being used. In other words, when a variable loses all its references Garbage collection marks this memory as âunreachableâ and releases it.
Execution context stack
A stack is the data structure that follows the Last In First Out (LIFO) principle (the last item to enter the stack will be the first item to be removed from the stack).
ECS stores execution context for all the functions. Execution context is defined as an object which stores local variables, functions, and objects.
In simple words, each function is pushed on the top of the sack.
JavaScript engine executes the function which is at the top of this stack.
As JavaScript engine has only one ECS, it can execute only one thing at a time which is at the top of the ECS. This is what makes JavaScript single-threaded.
You must have heard of stack overflow.
What does that mean? - ECS also has limited space. So, if we keep adding function on the top of the stack. At some point, there will not be more space to add more stack frames. At this point, we get a stack overflow error.
Consider the following example.
function heyJS() {
console.log("Hello you are awesome!!!!");
heyJS();
}
heyJS();
Well, that went into an infinite recursion and we have a stack overflow error.
So as I mentioned JavaScript is a simple threaded language, which means it has only one call stack ad therefore it can only execute one statement at a time.
Wait, we also heard about asynchronous programming in javascript.
So how does that work when only one task is allowed at a time?
Here comes Web APIâs and Callback queue.
Web APIâs
Web APIs are not part of the JS engine but they are part of the JavaScript Runtime Environment which is provided by the browser. JavaScript just provides us with a mechanism to access these APIâs. As Web APIs are browser-specific, they may vary from browser to browser. There may be cases where some Web APIs may be present in one browser but not in another.
Examples:-
document.getElementById();
document.addEventListerner();
setTimeOut();
setInterval();
Example:-
console.log(âFirst!â);
setTimeout(() => {
console.log(âSecond!â);
}, 1000 );
console.log(âThird!â);
/*
OutPut:-
First
Third
Second
*/
Itâs weird, right?
âSecondâ is inside the setTimeout so that will executed after 1 second.
What exactly happens behind the scene?
After 1-second WebAPI will get notified, hey you have code that you need to execute now.
WebAPI âOh itâs console.log() I need to execute that, but I canât execute this directly. Letâs send it to Callback Queueâ
âHey, Queue here is the callback please add this on your list and execute itâ.
Callback Queue
Callback Queue or Message Queue is a queue data structure that follows the First In First Out principle (item to be inserted first in the queue will be removed from the queue first). It stores all the messages which are moved from the event table to the event queue. Each message has an associated function. The callback queue maintains the order in which the message or methods were added in the queue.
Event loop
The event loop continuously checks if the execution context stack is empty and if there are any messages in the event queue. It will move the method from the callback queue to ECS only when the execution context stack is empty.
Callback Queue
âHey, Event loop please check if ECS is empty. I have some callbacks that you need to push into ECSâ.
Event Loop
âQueue please give me callbacks ECS is empty now, I will push them on the stack to execute them.â
And finally, in the end, we will get out output.
// First
// Third
// Second
This is just an overview of how JavaScript Engine works.
JavaScript engine is way more complex than how we discuss here today.
I will try to get deeper into the JavaScript engine in some of my future Articles.
In the next article of this series, I will explain Javascript Types, values, and variables.
Hope you like it, if yes **like & share.**
Thanks for your time.
Happy codingâŠ.
Posted on October 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.