How does the JS Engine work?
The JavaScript Engine has 6 main components that work together as a whole. We will take a short look into all of them, and show how are they connected and how they work together.
- Parser - The source code is sent to a decoder which decodes the contents inside the HTML script tag into tokens that are sent to the parser. The engine tries to avoid parsing code that’s not necessary right away in order to save time.
- AST - The parser creates nodes based on the tokens it receives. With these nodes, it creates an Abstract Syntax Tree (AST).
- Interpreter - It generates byte code, by reading the code line by line. Once the byte code is generated, the AST is deleted and memory space is cleared up.
- Profiler - Monitors and watches code to optimize it.
- Compiler - Works ahead of time and creates a translation of the code that has been written and compiles it down to a lower level language that machines can read.
- Optimized code - Code needs to be optimized to be run quicker. ![enter image description here]
Call Stack and Memory Heap
The Call Stack and the Memory Heap are both important parts of the JS engine.
The Call Stack keeps track of where we are in the code. It uses first in and last out and stacks for example functions.
The Memory Heap stores and writes information, where memory is allocated, used, and removed.
The Call Stack calls a function from the Memory Heap and after executing removes it from the stack. When the maximum call stack has been reached, e.g. with an infinite loop, is called a stack overflow.
