When you run JavaScript (in a browser or Node.js), the JavaScript engine (e.g., V8) follows these main steps:
The engine reads the source code and checks for syntax errors.
It converts the code into an Abstract Syntax Tree (AST).
The AST is compiled into bytecode for faster execution.
Code is executed inside an Execution Context.
All Execution Contexts are managed in the Call Stack.
When JavaScript starts running:
Global Execution Context (GEC) is created:
- A global object is created (
windowin browsers,globalin Node). thisis set to the global object (non-strict mode).- Variables and functions are hoisted.
Function Execution Context (FEC) is created when a function is called:
- New memory is allocated for local variables.
- Scope chain is created.
thisvalue is determined.
The call stack is a Last In, First Out (LIFO) data structure that keeps track of function execution.
Step 1: The script starts → GEC is pushed to the stack.
Step 2: When a function is called → its FEC is pushed on top.
Step 3: When a function finishes → its EC is popped off.
Step 4: The process continues until the stack is empty.
function greet() {
console.log('Hello');
}
function start() {
greet();
console.log('Start function done');
}
start();- Push GEC
start()is called → pushstart()ECgreet()is called → pushgreet()ECconsole.log("Hello")runs → popgreet()ECconsole.log("Start function done")runs → popstart()EC- GEC finishes → stack empty
Step 1: [ GEC ]
Step 2: [ GEC, start() ]
Step 3: [ GEC, start(), greet() ]
Step 4: [ GEC, start() ]
Step 5: [ GEC ]
Step 6: [ empty ]
- Single-threaded: Only one call stack → no parallel execution.
- Stack overflow: Happens when too many nested calls occur (e.g., infinite recursion).
- Async behavior: Asynchronous code doesn't block the stack — it's handled by the event loop and callback queue, which push functions onto the stack when ready.
"JavaScript executes code inside an execution context, starting with the Global Execution Context. Function calls create new Function Execution Contexts, which are pushed onto the call stack in a LIFO manner. Once a function finishes, it's popped from the stack. Since JavaScript is single-threaded, only one function executes at a time."