JavaScript  Engine

JavaScript Engine

No, It is not hardware it is just a software code that is present in every browser. In this blog, I will talk about the JavaScript (js) engine.

JavaScript Runtime Environment(JSE)- Every browser has JSE in it. JSE consists of a Js engine that executes the JS code and it is also the heart of JSE. JSE contains a Js engine, API, callback queue, microtask queue, and an event loop.

Screenshot_33.jpg

Inside Js engine there are different steps for getting the output. The Js code that we write at first go for parsing. In parsing step, our code is broken down in tokens like in the below image we can see that let, a, =, and 7 is broken down in tokens.

Screenshot_34.jpg

The code is then passed to a syntax parser the job of this is to take our code and broke it in Abstract Syntax Tree(AST).

Screenshot_35.jpg

Now understand the interpreter and compiler.

Interpreter- The job of the interpreter is to take the code and execute it line by line. It is fast.

Compiler- In this our whole code is compiled first even before execution and a new code is formed which is the optimized version of our code and then it is executed. The optimized code runs very fast. It is efficient.

Now, coming to the main part. When JavaScript was first invented by Brendan Eich, it uses an interpreter to execute the code. But modern browser like the V8 engine uses Just In Time(JIT) compilation. Which uses both interpreter and a compiler for code execution. Compilation and execution go hand in hand. Our AST goes to an interpreter and it goes for execution and at the same time compiles the code which is executed line by line by the interpreter.

Screenshot_36.jpg

In some engines, there is also AOT(ahead of time) compilation. It takes the code and compiles it before execution.

A memory heap is used for storing variables. A garbage collector(GC) is used for collecting garbage value. O is for optimization. Garbage collection uses a mark and sweep algorithm for freeing memory.

Screenshot_37.jpg

At present V8 engine of google is the best engine for JavaScript.

Screenshot_38.jpg

I have read all this from the Namaste JavaScript series by Akshay Saini. If you want to fall in love with JavaScript then you should learn from this.