【JavaScript】JavaScript Engine and Runtime
The actual contents comes from The Complete JavaScript Course 2021.
If you have interests, you can check The Complete JavaScript Course by Jonas Schmedtmann.
JavaScript Engine
JavaScript Engine is a computer program that executes JavaScript code.
Every browser has its own JavaScript engine, the most well-known engine is Google V8.
Call Stack and Heap
The call stack is where our code is actually executed, using something called execution contexts.
The heap is an unstructured memory pool, which stores all the objects that our application needs.
Compilation vs Interpretation
Just-In-Time Compilation
Modern JavaScript engine use a mix between compilation and interpretation, which is called just-in-time compilation.
This approach compiles the entire code into machine code at once, and then executes it right away.
The execution happens immediately after a compilation.
Just-In-Time Compilation in Detail
- Parse the code, which means to read the code, and the code is parsed into a data structure called AST(Abstract Syntax Tree).
- Takes the generated AST and compiles it into machine code.
- The machine code then gets executed right away.
- The first unoptimized code is being optimized and recompiled during the already running program execution, this process can be done multiple time.
How AST Works?
This works by first splitting up each line of code into pieces that are meaningful to the language, like the const or function keywords, and then saving all these pieces into the tree in a structured way.
This step also checks if there’re any syntax errors.
JavaScript Runtime (Browsers)
-Web APIs are functionalities provided to the engine, but are not part of the JavaScript language itself.
JavaScript gets access to these APIs through global window object.
-Callback queue, is a data structure that contains all the callback functions that are ready to be executed.
-Event Loop, takes callback functions from the callback queue and puts them in the call stack, so that they can be executed.
JavaScript Runtime (Node.Js)
Since we don’t have a browser, we don’t have WEB APIs because it’s the browsers who provide these.