Sub topic 3
Block Scope and Function Scope
This chapter assumes you can declare variables with var, let, and const, write and call functions, and read basic control flow such as if, for, and switch. The previous chapter showed that where code is written decides what it can see. This chapter covers the size of the region each declaration belongs to. That region decides which variables a closure can capture and whether two closures share one variable or each get their own.
Two Kinds of Scope
JavaScript has two main kinds of local scope:
- Function scope is the region of a whole function body. A
vardeclaration belongs to the nearest enclosing function, wherever it appears inside that function. - Block scope is the region between a pair of curly braces: an
ifbody, a loop body, aswitchbody, atryorcatchblock, or a bare{ ... }. Declarations made withlet,const, andclassbelong to the nearest enclosing block.
A block that sits inside a function is still part of that function. A var inside the block ignores the braces and attaches to the function. A let stays inside the braces.
function demo() {
if (true) {
var a = 'var';
let b = 'let';
const c = 'const';
console.log(a, b, c); // var let const
}
console.log(a); // 'var'
console.log(typeof b); // 'undefined' (b does not exist here)
console.log(typeof c); // 'undefined'
}
demo();typeof is used here because reading b directly outside the block would throw a ReferenceError. There is no b in the function's scope at all.
Hoisting and the Temporal Dead Zone
Every declaration is registered when its scope is entered, before any line in that scope runs. What differs is the state the variable starts in.
- A
varis created and set toundefinedstraight away. You can read it before its declaration line and you getundefined. - A
letorconstis created but left uninitialized. From the start of the block until the declaration line runs, the variable is in the temporal dead zone (TDZ). Any read or write in that window throws aReferenceError.
console.log(v); // undefined
var v = 1;
try {
console.log(l);
} catch (e) {
console.log(e.name); // ReferenceError
}
let l = 2;
console.log(l); // 2The TDZ catches a common shadowing mistake. When an inner block declares a name that also exists outside, the inner declaration covers the outer one for the whole block, including the lines above it.
const name = 'outer';
function greet() {
try {
console.log(name); // inner name is in its TDZ
} catch (e) {
console.log(e.name); // ReferenceError
}
const name = 'inner';
return name;
}
console.log(greet()); // 'inner'If you expected the first console.log to print 'outer', you hit the TDZ. The lookup stops at the nearest scope that declares name, and that scope is the function body, even though the declaration hasn't run yet. With var the same code would print undefined without any error, which makes the bug harder to find.
Redeclaration and Reassignment
var lets you declare the same name twice in one scope, and the second declaration quietly reuses the first variable. let and const reject this when the code is parsed, before anything runs.
var count = 1;
var count = 2; // allowed, same variable
console.log(count); // 2
let total = 1;
// let total = 2; // SyntaxError: Identifier 'total' has already been declared
total = 2; // reassignment is fine for let
console.log(total); // 2
const settings = { debug: false };
// settings = {}; // TypeError: Assignment to constant variable
settings.debug = true; // allowed: the object itself is not frozen
console.log(settings.debug); // trueconst fixes the binding, meaning which value the name points to. It does not make the value immutable. A closure that captures a const object can still see that object change.
Comparison Table
| Behavior | `var` | `let` | `const` |
|---|---|---|---|
| Scope | Nearest function (or global) | Nearest block | Nearest block |
| Readable before declaration | Yes, as `undefined` | No, TDZ `ReferenceError` | No, TDZ `ReferenceError` |
| Redeclare in same scope | Allowed | `SyntaxError` | `SyntaxError` |
| Reassign | Allowed | Allowed | `TypeError` |
| Top-level in a classic script creates a global object property | Yes | No | No |
| New binding per loop iteration | No | Yes | Yes (for `for...of` / `for...in`) |
Edge Cases Worth Knowing
Top-level `var` and the global object
In a classic browser script (not a module), a top-level var becomes a property of the global object. A top-level let or const does not.
// Run as a classic <script> in a browser
var g = 1;
let h = 2;
console.log(globalThis.g); // 1
console.log(globalThis.h); // undefinedIn ES modules and in Node.js CommonJS files, the top level is already a module scope, so neither line touches globalThis. This difference is one reason older scripts collided with each other's globals.
`switch` shares one block
All the case clauses of a switch sit inside a single block. Declaring the same const in two cases is a SyntaxError. Wrap each case in its own braces to give it a private block:
function describe(kind) {
switch (kind) {
case 'a': {
const msg = 'first';
return msg;
}
case 'b': {
const msg = 'second';
return msg;
}
default:
return 'unknown';
}
}
console.log(describe('a'), describe('b'), describe('z')); // first second unknown`catch` parameters and bare blocks
The parameter in catch (e) is block-scoped to the catch block. A bare { ... } block is legal on its own and is useful for limiting how long a temporary variable stays reachable:
{
const temp = 'only needed briefly';
console.log(temp.length); // 19
}
// temp is not reachable hereFunction declarations inside blocks
In strict mode and in modules, a function declared inside a block is scoped to that block. Non-strict code follows older legacy rules that can also expose the function in the enclosing function scope. Avoid relying on either behavior. If you need a function inside a block, assign a function expression to a const.
Why This Matters for Closures
A closure captures the variables of the scopes around it. The kind of scope decides how many separate variables exist. Each time a block runs, it creates fresh let and const bindings. A var, on the other hand, exists once per function call, no matter how many blocks mention it.
function withLet() {
const fns = [];
{
let n = 1;
fns.push(() => n);
}
{
let n = 2;
fns.push(() => n);
}
return fns.map((f) => f());
}
function withVar() {
const fns = [];
{
var n = 1;
fns.push(() => n);
}
{
var n = 2;
fns.push(() => n);
}
return fns.map((f) => f());
}
console.log(withLet()); // [1, 2]
console.log(withVar()); // [2, 2]In withLet, each arrow function captures a different n. In withVar, both blocks name the same function-scoped n, so both arrow functions read its final value. The loop-closure chapter later in this tutorial builds on this exact difference.
Common Errors
- Reading a block variable after its block ends. Move the declaration to the outer scope, or return the value out of the block.
- Shadowing that triggers the TDZ. If an inner
constreuses an outer name, every reference in that block points to the inner variable. Rename one of them. - Assuming
constfreezes objects. UseObject.freezeif you need a shallow immutable object. - Converting
vartoletblindly. Code that read avaroutside the block it was declared in will start throwing. Check every use before you convert.
Exercise
What does this code print, and why? function f() { if (false) { var x = 1; } return typeof x; } console.log(f());
Show answer
It prints 'undefined'. The var declaration is hoisted to the top of f even though the if body never runs, so x exists in the function scope with the value undefined. typeof undefined is 'undefined'. If x were declared with let, it would exist only inside the block, and typeof would still return 'undefined' because x would not be declared in the function scope at all.
Exercise
This code throws. Explain the error and fix it without renaming anything outside the function. let limit = 10; function check(n) { if (n > limit) { return 'too big'; } let limit = 5; return 'ok'; }
Show answer
The let limit inside check shadows the outer limit for the whole function body, so the comparison n > limit reads the inner limit while it is still in its temporal dead zone and throws a ReferenceError. Fix it by renaming the inner variable (for example, let localLimit = 5) or by moving the inner declaration into a separate block below the comparison so that it no longer shadows the outer limit at the point of comparison.
Exercise
Two arrow functions are created in two separate bare blocks. Both blocks assign to a variable named id, and the functions return id. Under what declaration keyword do the functions return different values, and why?
Show answer
With let or const, each block creates its own id binding, so each arrow function captures a different variable and returns that block's value. With var, both blocks refer to a single function-scoped id, so both arrow functions read the same variable and return whatever value was assigned last.