Module 4: Functions, Scope, and Closures
Scope, Hoisting, and the Temporal Dead Zone
Understand global, function, and block scope and when declarations become accessible.
Scope defines where a name can be accessed. let and const are block-scoped; var is function-scoped. A function can read variables from its outer lexical environment, which is the basis of closures.
if (true) {
const message = "inside block";
console.log(message);
}
// console.log(message); // ReferenceError
Hoisting is not moving code#
Before executing a scope, JavaScript creates bindings for declarations. Function declarations are initialized so they can be called earlier in the scope. var declarations are initialized to undefined, while let and const bindings cannot be accessed before their declaration is evaluated.
console.log(count); // undefined
var count = 2;
// console.log(total); // ReferenceError in the temporal dead zone
let total = 5;
The temporal dead zone (TDZ) is the period from entering a block until a let or const declaration is initialized. Do not rely on hoisting as a style technique; declare values before use for clearer code.
Lexical scope#
A function defined inside another function can access variables from the outer function. Its access is determined by where it is written, not simply where it is called. This is called lexical scoping.
Practice#
Create a block with let and const, then test access inside and outside it. Explain why the outside access fails.