Types of Execution Context
Types of Execution Context
Section titled “Types of Execution Context”Introduction
Section titled “Introduction”JavaScript has three types of execution contexts: global, function, and eval. Each is created at different times and serves a different purpose.
1. Global Execution Context
Section titled “1. Global Execution Context”Created when the JavaScript script first runs:
// This runs in the global execution contextconst globalVar = 'I am global';
function outer() { // Function execution context}- Only one global context exists
- It’s the default context
- In browsers:
this=window - In Node.js:
this=global - Remains active until the program ends
2. Function Execution Context
Section titled “2. Function Execution Context”Created every time a function is called (not defined):
function first() { // Function EC for first() function second() { // Function EC for second() } second();}
first();// Creates: Global EC → first() EC → second() EC- Each function call creates a new context
- Multiple function contexts can exist (stacked)
- Each has its own variable environment and
thisbinding
3. Eval Context
Section titled “3. Eval Context”Created when code is executed inside eval():
eval('var x = 10;'); // Creates an eval execution context- Rarely used (and discouraged)
- Has its own scope
- Can access the enclosing scope
Context Lifecycle
Section titled “Context Lifecycle”flowchart LR A["Script Starts"] --> B["Global EC Created"] B --> C["Function Called"] C --> D["Function EC Created"] D --> E["Function Returns"] E --> F["Function EC Destroyed"] F --> G["More Functions?"] G -->|Yes| C G -->|No| H["Program Ends"] H --> I["Global EC Destroyed"]Summary
Section titled “Summary”| Type | Created When | How Many Can Exist |
|---|---|---|
| Global | Script starts | 1 |
| Function | Function is called | Multiple (stacked) |
| Eval | eval() is called | Multiple |