Execution Context
The environment where JavaScript code is evaluated and executed.
What Is It?
The wrapper around running code that tracks everything needed for execution.
// When JavaScript runs this code, it creates an
// "execution context" — a container that holds:
//
// 1. Variable Environment (what variables exist)
// 2. Scope Chain (what outer scopes are accessible)
// 3. 'this' binding (what 'this' refers to)
const name = "Alice";
function greet() {
console.log("Hello, " + name);
}
greet();Execution Context =
Context Types
Three types of execution contexts in JavaScript.
1. Global Execution Context
Created when the script first runs. Only one per program.
// This runs in the Global Context: const app = "VisualJS"; console.log(app); // 'this' = window (browser) or globalThis
2. Function Execution Context
Created each time a function is called. Destroyed when it returns.
function add(a, b) {
// New context created here
const result = a + b;
return result;
// Context destroyed after return
}
add(2, 3); // creates context
add(5, 7); // creates another context3. Eval Execution Context
Created inside eval(). Rarely used and generally avoided for security reasons.
Creation & Execution
Every context goes through two phases.
// Source code:
var x = 5;
function greet(name) {
var message = "Hello " + name;
return message;
}
var result = greet("Alice");Before any code runs, the engine scans the entire scope. This is the Creation Phase.
Variable Environment
How var, let, and const are stored differently.
// In the CREATION phase:
var a = 1; // → stored as: a = undefined
let b = 2; // → stored in TDZ (not accessible yet)
const c = 3; // → stored in TDZ (not accessible yet)
function d() {} // → stored as: d = <full function>
// In the EXECUTION phase:
// a = 1 (assigned)
// b = 2 (initialized, exits TDZ)
// c = 3 (initialized, exits TDZ)| Declaration | Creation Phase | Before Init |
|---|---|---|
| var | undefined | undefined (accessible) |
| let | TDZ | ReferenceError |
| const | TDZ | ReferenceError |
| function | Full definition | Fully usable |
this Binding
'this' is determined when the execution context is created.
// Global context:
console.log(this); // window (browser) / globalThis
// Function context (non-strict):
function show() {
console.log(this); // window
}
// Function context (strict):
"use strict";
function show() {
console.log(this); // undefined
}
// Method context:
const obj = {
name: "Alice",
greet() {
console.log(this); // obj ← the calling object
}
};
// Arrow functions — no own 'this':
const arrow = () => {
console.log(this); // inherits from enclosing context
};FAQ
Common questions about execution context.