Execution Context
Execution context (EC) is defined as the environment in which JavaScript code is executed. By environment, I mean the value of this, variables, objects, and functions that the JavaScript code has access to at a particular time.
All JavaScript code needs to run in an environment, and that environment is called an execution context.
The default execution context is always the global context.
The global execution context is for variables and functions that are not inside any function.
Execution Context Stack (ECS)
It's a stack of execution contexts (last in, first out) that stores all the execution contexts created during the lifecycle of the script.
The global execution context is present by default at the bottom of the execution context stack.
While executing the global execution context code:
- Each function gets its own execution context & is pushed to the top of the execution context stack.
- The JS engine executes the function whose execution context is at the top of the execution context stack.
- Once all the code in the function is executed, the JS engine pops that function's execution context and starts executing the function below it.
How it works
- When the script starts, the Global Execution Context is created and pushed to the stack.
- When a function is called, a new execution context is created for that function and pushed on top.
- When the function finishes, its context is popped off the stack.
- Control returns to the context below it in the stack.
- This continues until the program finishes and the global context is popped.
This is the fundamental mechanism that drives how JavaScript executes code — understanding it helps you reason about scope, hoisting, closures, and the call stack.