Scope and Lifetime
Where a name is visible (scope) versus how long its value exists (lifetime), including lexical scoping, shadowing and closures.
What is it?
Two related but different questions:
- Scope: where in the code can this name be used?
- Lifetime: how long does the value exist while the program runs?
Common scope levels:
- Global: visible everywhere in the file or program. - Function: visible anywhere inside one function. - Block: visible only inside one { ... } block, such as an if or a loop body (JavaScript let/const, Java, C, Rust). Python has no block scope: a variable assigned inside an if is visible in the rest of the function.
Almost all modern languages use lexical (static) scoping: a name is resolved by looking at where the code is written, searching outward through the enclosing blocks and functions. Declaring a new variable with the same name as an outer one shadows it inside the inner scope.
A closure is a function that remembers variables from the scope where it was defined. Those variables live as long as the closure does, even after the outer function has returned. That's where scope and lifetime visibly diverge.
Explain like I'm 10
Scope is like who can hear you: a whisper in a meeting room is only heard there, an announcement over the building speakers is heard everywhere. Lifetime is how long a note stays pinned to the board. A closure is a backpack: a function leaves the room, but packs the notes it needs and carries them along.
Examples
Block scope, function scope and shadowing (JavaScript)
const level = "global";
function show() {
const level = "function"; // shadows the global 'level'
if (true) {
const level = "block"; // shadows the function's 'level'
console.log(level); // "block"
}
console.log(level); // "function"
}
show();
console.log(level); // "global"Closures keep variables alive (Python)
def make_counter():
count = 0 # local to make_counter...
def increment():
nonlocal count # ...but captured by increment
count += 1
return count
return increment
counter = make_counter() # make_counter has returned
print(counter()) # 1
print(counter()) # 2 'count' outlived its function callnonlocal tells Python that count refers to the enclosing function's variable. Without it, count += 1 would create a new local and raise UnboundLocalError.
Late binding in loops (Python) vs per-iteration let (JavaScript)
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2] all share the same 'i'
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2] default captures the current value
# JavaScript: 'let' creates a fresh binding per iteration, so this logs 0 1 2.
# With 'var' (function-scoped) it would log 3 3 3.
# for (let i = 0; i < 3; i++) setTimeout(() => console.log(i));How it works
Each function call and each block creates an environment: a table of names to values, linked to the environment it was written inside. Looking up a name walks this chain outward (local, then enclosing functions, then global, then built-ins) until it finds a match. Python names this order LEGB: Local, Enclosing, Global, Built-in.
Because the chain follows where code is written, not where it's called from, scoping is "lexical". (Dynamic scoping, which follows the call chain, survives mainly in shell scripts and Emacs Lisp.)
Lifetime is separate. A local is normally discarded when its function returns. But if a closure still references the environment, the runtime keeps it alive on the heap until nothing references it any more. Globals live for the whole program. In languages without GC (C, Rust), lifetime is tied to scope directly: a value is destroyed when its owning scope ends.
Name lookup walks outward (lexical scope chain)
+-- global ------------------------------+
| level = "global" |
| +-- show() --------------------------+|
| | level = "function" ||
| | +-- if block -------------------+ ||
| | | level = "block" <- found | ||
| | | console.log(level) | ||
| | +-------------------------------+ ||
| +------------------------------------+|
+----------------------------------------+Why does it exist?
Scopes let you reuse short, natural names (i, result, user) without colliding with code elsewhere, and keep each piece of state visible only to the code that needs it. Lexical scoping makes code readable: you can tell what a name refers to just by reading the surrounding text. Closures give functions private, persistent state without classes or globals.
When to use it
Declare every variable in the narrowest scope that works, as close as possible to where it's used. Use closures for callbacks, event handlers, factory functions, memoisation and small pieces of private state. Prefer block-scoped declarations (let/const in JavaScript) over function-scoped var.
When not to use it
Avoid global mutable variables: any code can change them, which makes bugs hard to trace and tests interfere with each other. Avoid shadowing names in ways that confuse readers (an inner user hiding an outer user a few lines up). Don't use closures to hold large data longer than needed; the captured values can't be garbage-collected while the closure is reachable.
Common mistakes
Assuming Python has block scope. A variable assigned inside an
iforforis still visible after the block.Assigning to an outer variable inside a Python function without
globalornonlocal, which creates a new local and often raisesUnboundLocalError.Using
varin a JavaScript loop with callbacks, so every callback sees the final loop value.Creating closures in a Python loop and expecting each to capture that iteration's value (they capture the variable, not the value).
Accidentally keeping large objects alive through a long-lived closure or event listener, causing a memory leak.
Practice exercises
- Easy:
Write a snippet with a global, a function-level and a block-level variable of the same name, and predict what each print/log statement outputs before running it.
- Medium:
Write
makeRateLimiter(maxCalls)that returns a function which returns true for the firstmaxCallscalls and false afterwards, using a closure for the counter. Do it in both Python and JavaScript. - Hard:
Implement a
memoize(fn)higher-order function using a closure over a cache. Then add a way to clear the cache and explain how the closure affects the cache's lifetime.
Interview questions
What is the difference between scope and lifetime?
Scope is the region of source code where a name can be referenced. Lifetime is the period during execution when the value actually exists in memory. A closure-captured variable is out of scope for the caller but its lifetime continues.
What is lexical scoping?
Resolving a name based on where the code is written: the lookup searches the enclosing blocks and functions in the source text, not the chain of callers at run time.
What is shadowing?
Declaring a variable in an inner scope with the same name as one in an outer scope. Inside the inner scope, the name refers to the new variable and the outer one is hidden.
Does Python have block scope?
No. Python has function, module (global), class and built-in scopes. Variables assigned inside if, for or while blocks remain visible in the rest of the function. Comprehensions do have their own scope.
What is a closure?
A function together with references to the variables of the scope it was defined in. It can read (and, with nonlocal in Python or directly in JS, modify) those variables even after the outer function has returned.
What is the difference between `var` and `let` in JavaScript scoping?
var is function-scoped and hoisted, so it's visible throughout the function. let and const are block-scoped and can't be used before their declaration (the temporal dead zone). In loops, let creates a new binding per iteration.
What does LEGB mean in Python?
The name lookup order: Local, Enclosing (outer functions), Global (module), Built-in. Python uses the first match it finds.
Why does this raise `UnboundLocalError`? `x = 1; def f(): print(x); x = 2`
Because x is assigned somewhere in f, Python treats it as local for the whole function. The print(x) runs before that local has a value. Use global x if you meant the module variable.
What is dynamic scoping and where is it still used?
Resolving names through the chain of active function calls instead of the source text. It's used in Bash and Emacs Lisp; most other languages use lexical scoping because it's easier to reason about.
How can closures cause memory leaks?
A closure keeps every variable it captures reachable. If the closure is stored somewhere long-lived (an event listener, a global cache, a timer) and captures large data, that data can never be collected until the closure itself is removed.