Skip to content

Latest commit

 

History

History
96 lines (61 loc) · 2.69 KB

File metadata and controls

96 lines (61 loc) · 2.69 KB

How JavaScript Code Executed? & Call Stack

JavaScript Code Execution Overview

When you run JavaScript (in a browser or Node.js), the JavaScript engine (e.g., V8) follows these main steps:

Parsing

The engine reads the source code and checks for syntax errors.

It converts the code into an Abstract Syntax Tree (AST).

Compilation (JIT – Just-In-Time Compilation)

The AST is compiled into bytecode for faster execution.

Execution

Code is executed inside an Execution Context.

All Execution Contexts are managed in the Call Stack.

Execution Context in Code Execution

When JavaScript starts running:

Global Execution Context (GEC) is created:

  • A global object is created (window in browsers, global in Node).
  • this is 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.
  • this value is determined.

Call Stack — The Manager of Execution

The call stack is a Last In, First Out (LIFO) data structure that keeps track of function execution.

How It Works:

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.

Example:

function greet() {
  console.log('Hello');
}

function start() {
  greet();
  console.log('Start function done');
}

start();

Call Stack Flow:

  1. Push GEC
  2. start() is called → push start() EC
  3. greet() is called → push greet() EC
  4. console.log("Hello") runs → pop greet() EC
  5. console.log("Start function done") runs → pop start() EC
  6. GEC finishes → stack empty

Diagram:

Step 1: [ GEC ]
Step 2: [ GEC, start() ]
Step 3: [ GEC, start(), greet() ]
Step 4: [ GEC, start() ]
Step 5: [ GEC ]
Step 6: [ empty ]

Important Interview Points

  • 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.

Interview Soundbite:

"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."