- A JavaScript Engine is a program that executes JavaScript code.
- Browsers (Chrome, Firefox, Safari, Edge) and Node.js use their own engines.
- It converts JavaScript code → Machine code so the computer can run it.
🔹 Popular JavaScript Engines
- V8 → Google Chrome, Node.js
- SpiderMonkey → Firefox
- JavaScriptCore (a.k.a. Nitro) → Safari
- Chakra → Old Microsoft Edge
🔹 How Does a JS Engine Work? (Step by Step)
-
Parsing
- Source code → Tokens (keywords, variables, operators).
- Tokens → Abstract Syntax Tree (AST).
Example:
let a = 10 + 20;→ Parsed into tree structure representing assignment, addition, values.
- Compilation / Interpretation
- Earlier: JavaScript was interpreted (line by line).
- Modern engines use JIT (Just-In-Time Compiler):
- Convert JS → Bytecode → Optimized Machine code.
- Runs faster than old interpreters.
- Execution
- Engine executes machine code on CPU.
- Uses Heap (memory) for variables/objects and Call Stack for function execution.
🔹 Example (Inside V8 Engine)
function add(a, b) {
return a + b;
}
console.log(add(2, 3));
- Parsing → builds AST for
add. - Interpreter → generates bytecode for quick execution.
- Profiler + Optimizer → if function
add()is called often, V8 optimizes it into highly efficient machine code. - Execution → CPU runs machine code, outputs
5.
🔹 JS Engine Components
- Memory Heap → Stores objects & variables.
- Call Stack → Keeps track of function calls.
- Garbage Collector → Frees memory (removes unused objects).
- Event Loop + Callback Queue → (with Web APIs, though technically outside engine, part of runtime like browser/Node).
🔹 Visualization
JS Code
↓
Parser → AST
↓
Interpreter → Bytecode
↓
JIT Compiler → Optimized Machine Code
↓
CPU executes
✅ Summary:
A JavaScript Engine is the heart of JS execution. It:
- Parses JS code into AST
- Compiles/interprets into machine code (via JIT)
- Executes on CPU using heap + call stack
- Manages memory via garbage collection