7. Scope & Environments
How variables find their values
When you write let x = 10 and later reference x, something has to connect
the name to the value. That "something" is an environment — and the rules
that decide which environment gets consulted are the language's scoping rules.
Scope seems simple until it isn't. Shadowing, nested blocks, functions referencing outer variables — all of these depend on getting the environment chain right. Let's build that chain from the ground up.
What is scope?
A scope is a region of your program where a particular name refers to a particular thing. Inside that region, the name is "in scope." Outside it, the name either doesn't exist or refers to something else.
let x = 1; // x is in scope from here...
{
let y = 2; // y is in scope only inside this block
print x + y; // 3 — x is still visible
}
print x; // 1 — still fine
print y; // Error! y is out of scope
The curly braces create a new scope. Variables declared inside it vanish when the block ends.
Lexical vs. dynamic scope
There are two fundamentally different ways a language can resolve variable names.
Lexical scope (also called static scope) means that a variable's scope is
determined by where it appears in the source text. If you can see the enclosing
let by reading the code, you can access the variable. This is what JavaScript,
Python, Rust, C, and almost every modern language uses.
Dynamic scope means that variable lookup follows the call chain, not the
nesting chain. If function A calls function B, B can see A's local variables.
This is what early Lisps, Bash, Emacs Lisp (by default), and Perl's local
keyword use.
let x = "global";
fn inner() {
print x; // What does this print?
}
fn outer() {
let x = "outer";
inner();
}
outer();
Under lexical scope, inner prints "global" — it was defined at the top
level, so it sees the top-level x. Under dynamic scope, inner prints
"outer" — it was called from outer, so it sees outer's x.
Lexical scope won because it's predictable. You can determine what every name refers to just by reading the code, without tracing the runtime call graph.
The environment chain
An environment is a map from names to values, plus a pointer to a parent environment. When you look up a variable, you check the current environment first. If it's not there, you follow the parent pointer and check the next one. This continues until you either find the variable or run out of environments (which means the variable is undefined).
class Environment {
constructor(parent = null) {
this.vars = new Map();
this.parent = parent;
}
define(name, value) {
this.vars.set(name, value);
}
get(name) {
if (this.vars.has(name)) return this.vars.get(name);
if (this.parent) return this.parent.get(name);
throw new Error(`Undefined variable: ${name}`);
}
set(name, value) {
if (this.vars.has(name)) {
this.vars.set(name, value);
return;
}
if (this.parent) return this.parent.set(name, value);
throw new Error(`Undefined variable: ${name}`);
}
}
Three operations: define creates a new binding in the current environment,
get reads a value by walking the chain, and set updates an existing
binding by walking the chain. Notice that define never walks the chain — it
always binds in the current environment, even if the name exists in an outer
one.
Block scope vs. function scope
Some languages create a new environment for every { } block (block scope).
Others only create new environments for function bodies (function scope).
JavaScript has both: var is function-scoped, let and const are block-scoped.
C, Rust, and most modern languages are block-scoped. Python is function-scoped
(a for loop variable leaks into the enclosing function).
In our implementation, every block gets its own environment:
function executeBlock(statements, parentEnv) {
const env = new Environment(parentEnv);
for (const stmt of statements) {
execute(stmt, env);
}
// env is discarded when the block ends
}
When the block finishes, its environment object becomes unreachable and gets garbage collected. The variables declared inside it effectively disappear.
Walking the chain: a concrete example
Let's trace how the environment chain resolves variables in a nested program:
let x = 1;
{
let x = 2;
{
let y = 3;
print x + y; // ?
}
print x; // ?
}
print x; // ?
The environments look like this at the deepest point:
When the innermost block runs print x + y:
- Look up
xin block 2 — not found. - Walk to parent: look up
xin block 1 — found! Value is2. - Look up
yin block 2 — found! Value is3. - Result:
5.
When block 1 runs print x:
- Look up
xin block 1 — found! Value is2.
When the top level runs print x:
- Look up
xin global — found! Value is1.
Shadowing
When an inner scope defines a variable with the same name as an outer scope, the inner binding shadows the outer one. The outer variable still exists — it's just unreachable from within the inner scope.
let x = "outer";
{
let x = "inner";
print x; // "inner" — shadow hides the outer x
}
print x; // "outer" — the outer x was never touched
This works naturally with our environment chain. The inner define creates a
new binding in the inner environment. The get method finds it before ever
reaching the parent, so the outer binding is effectively invisible.
Shadowing is useful but can be confusing. Some languages (like Rust) allow it freely. Others (like some linters for JavaScript) warn about it.
The scope stack in a compiler
In a tree-walking interpreter, environments are runtime objects with parent pointers. But what about a compiler that produces bytecode? The compiler doesn't execute the code — it just translates it. It needs to know about scopes at compile time to emit the right instructions.
The compiler maintains a scope stack — a compile-time analog of the environment chain. Each scope tracks which local variables are defined and at what stack slot:
class Compiler {
constructor() {
this.scopes = [[]]; // stack of scopes, each a list of locals
}
beginScope() {
this.scopes.push([]);
}
endScope() {
const scope = this.scopes.pop();
// Emit OP_POP for each local to clean up the stack
for (let i = 0; i < scope.length; i++) {
this.emit(OP_POP);
}
}
declareLocal(name) {
const scope = this.scopes[this.scopes.length - 1];
scope.push({ name, depth: this.scopes.length - 1 });
}
resolveLocal(name) {
// Walk scopes from innermost to outermost
for (let i = this.scopes.length - 1; i >= 0; i--) {
const scope = this.scopes[i];
for (let j = scope.length - 1; j >= 0; j--) {
if (scope[j].name === name) return { scope: i, slot: j };
}
}
return null; // must be a global
}
}
When the compiler encounters let x = ..., it calls declareLocal("x"). When
it encounters a reference to x, it calls resolveLocal("x") and emits either
OP_GET_LOCAL slot (if found) or OP_GET_GLOBAL "x" (if not found in any
local scope).
The key difference from the runtime environment: the scope stack exists only during compilation. By the time the VM runs, all local variable references have been resolved to stack slot indices — no name lookups at runtime.
Putting it together
Scope and environments are the backbone of every programming language. The core ideas are simple:
- An environment is a name-to-value map with a parent pointer.
- Variable lookup walks the chain from inner to outer.
- Lexical scope means the chain follows the source code nesting.
- Shadowing happens naturally when inner scopes redefine a name.
- A compiler resolves scopes at compile time, converting names to indices.
With this foundation, we're ready to tackle the trickiest scope-related concept in language implementation: closures — functions that capture variables from their enclosing scope and carry them along even after that scope has ended.
Try It Yourself — Scope Explorer
Type a program with nested blocks and variables. Watch the environment chain grow and shrink as scopes open and close, and see how variable lookups walk the chain to find their values.