JS Engine is a program that executes the JS code, every browser has its own JS Engine following are some of the examples.
- Chrome - V8
- Edge - Chakra
- Safari - Nitro
- Firefox - Spider Monkey
But before that, we need to know the difference between compilation and Interpretation.
- The entire Source code is converted into machine code at once and written to a binary file 0's and 1's which can be executed later processor.
The Source Code gets Complied and covert the portable file (machine code) and then its portable files get executed and we are now able to run the program.
It's a 2 step process 1. compilation and 2. Execution.
Always remember the execution would take place after compilation only.
For Ex. whatever files or programs you are now executing are already complied with are ready to be executed as you are just hitting the trigger to execute them.
- The interpreter Runs through the source code and executes it line-by-line.
JS initially used to be interpreted language, and the problem with interpreted language is they are much slower.
Whereas in modern JS, low/slow performance is not at all acceptable, However, modern JS Engine, now uses a mix of both i.e Compilation and interpretation this is called Just-in-time compilation.
- The entire Source code is converted into machine code, at once then executed immediately.
And here no portable file is created, hence code is executed immediately, which is a lot faster than executing the code line-by-line.
Where Source code is parsed and then converted into Abstract Syntax Tree (AST), this is very different from the DOM tree.
Now, here is the splitting of each line of code meaningful language. Ex: const, let, function, etc. Keywords
This piece of code is then saved into the tree in a structured way.
It also checks if there is only a syntax error. This tree then shall be used to machine code.
- However modern JS Engine uses very clever optimization, strategies.
- Like they create a very unoptimized version of machine code, in the beginning, just so that they can start executing the code as fast as possible.
- In the Background, this code is optimized and re-complied in already/ongoing running execution, this can be done multiple times without ever stopping the execution.
- This process makes modern JS fast, all this parsing, compilation, execution, Optimization happens in some thread inside JS Engine, which can be accessed from our source code.
By: Moreshwar P