Let me explain execution context and related concepts in JavaScript in a structured manner.
Execution Context is the environment in which JavaScript code is executed. It contains information about the code's environment, variables, functions, and the scope chain. To fully understand execution context, you need to understand several related concepts:
Here's the order of concepts you should understand:
- Memory Allocation (Hoisting):
// Before code execution, memory is allocated for variables and functions
console.log(x); // undefined (not error)
var x = 5;
sayHello(); // Works!
function sayHello() {
console.log("Hello");
}
- Lexical Environment:
// The physical location where code is written
function outer() {
let a = 10;
function inner() {
console.log(a); // can access 'a' due to lexical environment
}
inner();
}
- Scope Chain:
let global = "global";
function outer() {
let outer = "outer";
function inner() {
let inner = "inner";
console.log(inner, outer, global); // can access all variables
}
inner();
}
- Types of Execution Context:
a. Global Execution Context:
// Created when JavaScript code starts running
var globalVar = "I'm global";
function globalFunc() {
console.log("Global function");
}
b. Function Execution Context:
function example() {
// New execution context is created when function is called
var functionVar = "I'm local";
}
c. Eval Execution Context (less common):
eval('console.log("eval context")');
- Execution Context Stack (Call Stack):
function first() {
second();
console.log("first");
}
function second() {
third();
console.log("second");
}
function third() {
console.log("third");
}
first();
// Output:
// "third"
// "second"
// "first"
- Execution Context Creation Phases:
a. Creation Phase:
function example() {
// 1. Create Arguments object
// 2. Set up scope chain
// 3. Create variable environment
// 4. Set value of 'this'
var x = 10;
console.log(x);
}
b. Execution Phase:
function example() {
var x = 10; // Now actual value assignment happens
console.log(x); // Now code is executed line by line
}
Complete Example Putting It All Together:
let globalVar = "global";
function outer() {
let outerVar = "outer";
function inner() {
let innerVar = "inner";
console.log(innerVar); // "inner"
console.log(outerVar); // "outer"
console.log(globalVar); // "global"
}
inner(); // Creates new execution context
}
outer(); // Creates new execution context
Understanding these concepts helps in:
- Variable scope and accessibility
- Closure behavior
- This keyword binding
- Function execution order
- Memory management
- Debugging code
Key Points to Remember:
- Each execution context has its own variable environment
- The scope chain allows access to outer variables
- The call stack manages execution context order
- Hoisting affects variable and function declarations
- Lexical scope determines variable accessibility
This hierarchical understanding helps in writing better JavaScript code and debugging issues related to scope and variable access.