Execution Context & Call Stack

ยท

1 min read

How JavaScript Code Executes

JavaScript uses a single-threaded model with an event loop. It executes code in two phases:

  1. Creation Phase: Memory allocation for variables and functions.

  2. Execution Phase: Runs the code line by line.

Example:

jsCopyEditconsole.log("Start");

function greet() {
    console.log("Hello!");
}

greet();

console.log("End");

โœ… Execution Order:

  1. "Start" prints.

  2. greet() is called, and "Hello!" prints.

  3. "End" prints.

๐Ÿ›  Call Stack Visualization:

  • console.log("Start") โ†’ Pushed & executed.

  • greet() โ†’ Pushed, executes console.log("Hello!"), then popped.

  • console.log("End") โ†’ Pushed & executed.

ย