Sub topic 3
Block Scope and Function Scope
This chapter assumes you can declare variables with var, let, and const, and that you read the previous chapter on lexical scope. In that chapter, the place where you write code decided what it can see. In this chapter, the keyword you use to declare a variable decides how large its scope is.
Two Kinds of Boundaries
JavaScript has two main scope boundaries inside a program:
- Function scope is the body of a function. A
vardeclaration belongs to the nearest enclosing function, or to the global scope if no function encloses it. - Block scope is any pair of curly braces: an
ifbody, a loop body, or a bare{ }block. Aletorconstdeclaration belongs to the nearest enclosing block.
| Keyword | Scope | Hoisted | Access before declaration | Reassignable |
|---|---|---|---|---|
| `var` | Function | Yes, initialized to `undefined` | Returns `undefined` | Yes |
| `let` | Block | Yes, but uninitialized | Throws `ReferenceError` | Yes |
| `const` | Block | Yes, but uninitialized | Throws `ReferenceError` | No |
Seeing the Difference
function demo() {
if (true) {
var a = 'var inside if';
let b = 'let inside if';
const c = 'const inside if';
console.log(b, c); // both visible here
}
console.log(a); // 'var inside if'
console.log(typeof b); // 'undefined', b does not exist here
}
demo();
console.log(typeof a); // 'undefined', a stayed inside demoThe var a declaration ignores the if braces and attaches to demo. It still stops at the function boundary, so nothing leaks out of demo. The let and const declarations stay inside the if block.
Hoisting and the Temporal Dead Zone
All three declarations are hoisted. The engine registers the name when it enters the scope. The difference is what the name holds before the declaration line runs.
function hoisting() {
console.log(x); // undefined
var x = 1;
try {
console.log(y);
} catch (err) {
console.log(err.name); // 'ReferenceError'
}
let y = 2;
}
hoisting();The stretch between the start of the block and the let y line is called the temporal dead zone (TDZ). Inside it, the variable exists but cannot be read. This turns silent undefined bugs into loud errors, so it helps you.
Common Errors
- Expecting
varto stay inside a block. Avarin aniforforbody is visible in the whole function. This causes the loop bug covered later in this tutorial. - Confusing
constwith immutability.constprevents reassigning the binding. It does not freeze the object.const list = []; list.push(1);is valid. - Shadowing by accident. A
letinside a block with the same name as an outer variable hides the outer one for that block only.
let level = 'outer';
{
let level = 'inner';
console.log(level); // 'inner'
}
console.log(level); // 'outer'Why This Matters for Closures
A closure captures the variables in scope where its function was created. The keyword you use decides which scope that is. With let, each block, and each loop iteration, can get its own variable. With var, everything in the function shares one variable.
Exercise
What does this code log, and why? function test() { for (var i = 0; i < 2; i++) {} console.log(i); } test();
Show answer
It logs 2. The var declaration is function-scoped, so i still exists after the loop ends and holds its final value. With let, console.log(i) would throw a ReferenceError because i would only exist inside the loop.
Exercise
Does this code throw an error? const config = { debug: false }; config.debug = true;
Show answer
No. const prevents reassigning the config binding, but the object it points to can still be changed. Writing config = {} would throw a TypeError.