Execution Context: Where JavaScript Variables Actually Live
# Execution Context: Where JavaScript Variables Actually Live
Run this code and predict the output before you read on:
```js
console.log(name); // What prints here?
var name = "Rakibul";
greet();
function greet() {
console.log("Hello, " + name);
}
```
The first `console.log` prints `undefined`, not an error — even though `name` has not been assigned yet. And `greet()` works even though it is called before its definition in the file. Neither of these is an accident. Both happen because of the **execution context**: the environment JavaScript creates every time your code runs, and the place where variables actually live while a program executes.
At Ovlyc, this is the concept we point to whenever a developer asks "why does this variable exist here, but not there?" — because once you understand execution contexts, hoisting, scope, and `this` all stop being separate mysteries and become consequences of one mechanism.
## What Is an Execution Context?
An execution context is a container that JavaScript creates to run a piece of code. It holds everything that code needs: its variables, its functions, a reference to the scope it can see, and the value of `this`. You never see it directly — it is an internal engine concept — but it decides what your code can and cannot access at any moment.
There are three kinds:
**1. The global execution context**
Created once, when your program starts. In a browser it lives on the `window` object; in Node.js it lives on the `global` object. Top-level `var` declarations and function declarations become properties of this context. There is only ever one global context per program.
**2. A function execution context**
Created every time a function is called. Each call gets its own fresh context — which is why a recursive function can call itself many times without its variables overwriting each other. When the function returns, its context is destroyed (unless a closure keeps it alive).
**3. The eval execution context**
Created by code run inside `eval()`. Rare in modern code, and best avoided — but it follows the same rules.
The engine manages these contexts on a stack — the **execution context stack**, which is the same call stack you already know from earlier articles in this series. The context on top of the stack is the one currently running. Call a function, and a new context is pushed. Return from it, and it is popped off.
## The Two Phases: Creation, Then Execution
Every execution context is built in two phases, and this is where most "weird" JavaScript behaviour comes from.
### Phase 1: The creation phase
Before a single line of your code runs, the engine scans the code inside the context and sets up its environment:
- **The variable environment is created.** Memory is reserved for every variable and function declared in that scope.
- **Function declarations are fully initialised.** The function object is created and stored, so the function can be called before its definition appears in the file.
- **`var` declarations are initialised to `undefined`.** The name exists, but it has no value yet.
- **`let` and `const` declarations are created but left uninitialised.** They exist in a "temporal dead zone" — referencing them before their declaration throws a `ReferenceError`.
- **The scope chain is set up.** The context records a reference to its outer scope, so it knows where to look when a variable is not found locally.
- **`this` is determined.** For a function call, `this` depends on how the function was called.
### Phase 2: The execution phase
Now the engine runs the code line by line, top to bottom, assigning real values to the variables that were reserved in the creation phase.
This two-phase model explains the opening example. During the creation phase of the global context, `name` is reserved and set to `undefined`, and `greet` is fully initialised as a function. So when the execution phase starts, `console.log(name)` finds the name — with the value `undefined` — and `greet()` can be called even though its definition comes later in the file.
## Hoisting Is Just the Creation Phase
"Hoisting" sounds like the engine moves your declarations to the top of the file. It does not move anything. What you are seeing is the creation phase doing its setup before execution begins:
```js
console.log(a); // undefined — not an error
var a = 5;
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 10;
sayHi(); // "Hi!" — works fine
function sayHi() {
console.log("Hi!");
}
```
- `var a` is hoisted and initialised to `undefined`, so reading it early gives `undefined`.
- `let b` is hoisted too — the name is known to the context — but it is left uninitialised, so reading it early throws.
- `function sayHi` is hoisted and fully initialised, so calling it early works.
The practical rule is simple: **declare variables before you use them, and prefer `let` and `const`.** The temporal dead zone is not a trap; it is the language telling you that reading a variable before its declaration is a mistake worth catching.
## The Scope Chain: How Variables Are Found
Every execution context carries a reference to its **lexical environment** — the scope where the code was written, not where it was called. When the engine needs a variable, it searches outward through this chain: the current context first, then the context that encloses it, and so on, until it reaches the global context. If it finds nothing, you get a `ReferenceError`.
```js
const company = "Ovlyc"; // global scope
function buildWebsite() {
const framework = "Next.js"; // function scope
function renderPage() {
// renderPage can see framework AND company,
// because the scope chain links it outward
console.log(company + " builds with " + framework);
}
renderPage();
}
buildWebsite();
```
`renderPage` does not define `framework` or `company`, yet it can use both. The engine walks its scope chain: `renderPage`'s own environment, then `buildWebsite`'s environment (where `framework` lives), then the global environment (where `company` lives).
This is lexical scoping: **a function can see the variables of the place where it was written.** It does not matter where the function is called from — what matters is where it was defined. That single rule is what makes closures possible.
## Closures: When a Context Refuses to Die
Normally, a function execution context is destroyed when the function returns. But if an inner function keeps a reference to the outer function's variables, the engine keeps that outer environment alive. That surviving environment is a **closure**:
```js
function createCounter() {
let count = 0; // lives in createCounter's context
return function () {
count += 1;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
```
`createCounter` has returned, so its execution context should be gone. But the returned function still references `count`, so the engine preserves that variable environment. Each call to `counter()` increments the same `count` — a private variable that nothing else in the program can touch.
Closures are everywhere in real applications: event handlers that remember state, module patterns that hide private data, React hooks that keep values between renders. They are not a special feature; they are what naturally happens when an execution context outlives its function call.
## `this` Is Decided Per Context
Every function execution context also carries a value of `this`, and it is decided at call time — by *how* the function was called, not where it was written:
```js
const user = {
name: "Rakibul",
greet() {
console.log("Hello, " + this.name);
},
};
user.greet(); // "Hello, Rakibul" — this is user
const greetFn = user.greet;
greetFn(); // "Hello, undefined" — this is the global object (or undefined in strict mode)
```
The same function, two different `this` values. In the first call, `this` is `user` because the function was called as a method of `user`. In the second, it was called as a plain function, so `this` is no longer `user`. Arrow functions are the exception: they do not create their own `this` at all, and instead borrow it from the enclosing context.
This is the most common source of `this` bugs in JavaScript — a method passed as a callback loses its object. Knowing that `this` is set per execution context, at call time, tells you exactly why it happened and how to fix it (bind it, wrap it, or use an arrow function).
## A Mental Model You Can Keep
When you read any JavaScript code, picture this:
1. The engine creates a context for the code it is about to run.
2. In the creation phase, it reserves memory for all declarations, initialises functions and `var` to `undefined`, and wires up the scope chain and `this`.
3. In the execution phase, it runs the code line by line, assigning real values.
4. When a function is called, a new context is pushed on top of the stack; when it returns, it is popped off.
5. If an inner function still needs an outer context's variables, that environment survives as a closure.
Hoisting, the temporal dead zone, lexical scope, closures, and `this` are not five unrelated rules. They are five consequences of this one model. Learn the model once, and each of them becomes predictable.
At Ovlyc, we use this mental model in code reviews whenever a bug smells like scope: a variable that is `undefined` at the wrong moment, a callback that lost its `this`, a loop variable that all closures share. Almost every time, the answer is in the context — which environment the code is running in, and what was set up in its creation phase.
In the next article, we will leave the browser behind and look at Node.js — what it actually is, how it runs JavaScript outside the browser, and why the same language behaves differently on a server.
Related Articles
What Is Node.js? JavaScript Beyond the Browser
Learn what Node.js is, how its V8 engine, libuv, and event loop work, and when to use it for APIs, real-time apps, and full-stack JavaScript.
Microtask vs Macrotask: Why Promises Jump the Queue in JavaScript
Why a zero-delay timer loses to a promise: JavaScript's microtask and macrotask queues explained, with examples of promises, timers, and event-loop starvation.
Explain the JavaScript Event Loop: How One Thread Handles Everything
How JavaScript's single thread stays responsive: the call stack, callback and microtask queues, timers, and why blocking the loop freezes everything.
Call Stack + Heap + Memory: How JavaScript Stores and Runs Your Code
Learn how JavaScript's call stack and heap work together — why recursion overflows, why objects share references, and where memory leaks come from.