What is an execution context made of?
An execution context in JavaScript consists of three main components - internal structures the engine creates to run your code.
The structure of an execution context
Every context (global or a function's) includes:
- Variable Environment (VE)
- Lexical Environment (LE)
- This Binding
1. Variable Environment
Holds variables and functions declared with var and function (not let/const!).
- It's set up when the context is created.
- Used to initialize variables and functions.
- Available only within the current context.
Example:
function test() {
var a = 10;
function inner() {}
}Here, a and inner are part of test's Variable Environment.
2. Lexical Environment
Handles variable lookup and closures. It holds:
- variables declared with
letandconst; - references to outer environments (the outer lexical environment reference);
- the function as a "lexical environment".
You can picture it as a "scope chain".
Example:
let x = 10;
function outer() {
let y = 20;
function inner() {
let z = 30;
console.log(x, y, z);
}
inner();
}
outer();The Lexical Environment of inner() contains:
- its own variable
z - a reference to
outer()'s environment (whereyis) - and a reference to the global environment (where
xis)
It is exactly this Lexical Environment that makes closures possible.
3. This Binding
Determines which object this refers to in a given context.
It depends on how the function is called:
| Way of calling | Value of this |
|---|---|
| Globally (in the browser) | window |
| In a function (strict mode) | undefined |
| In an object's method | the object itself |
Via call, apply, bind | the value passed manually |
| In an arrow function | taken from the outer context |
Example:
const obj = {
name: "Tim",
show() {
console.log(this.name);
}
};
obj.show(); // this = obj -> "Tim"Summary structure
Every execution context looks roughly like this:
Execution Context {
LexicalEnvironment: {
EnvironmentRecord: { let, const },
OuterEnvironmentReference: <reference to the outer LE>
},
VariableEnvironment: {
EnvironmentRecord: { var, function },
OuterEnvironmentReference: <reference to the outer LE>
},
ThisBinding: <value of this>
}A visual example
let a = 1;
function outer() {
var b = 2;
function inner() {
let c = 3;
console.log(a, b, c);
}
inner();
}
outer();When inner() is called:
- A new Execution Context is created, containing:
- Variable Environment:
[] - Lexical Environment:
{ c: 3 } - This Binding:
undefined(strict mode)
- Variable Environment:
- It has an Outer Environment Reference -> outer -> global,
which lets it find
banda.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.