Quiz
Warm-up from lesson 1-3: a `for (var i ...)` loop pushes three arrow functions that log `i`. Why do all three print 3?
Hoisting: declarations move up
Before running a scope, JavaScript registers every declaration in it first. What differs is the initial value:
var x = 10hoists the name to the top of the function, set toundefined. The assignment stays where you wrote it. Reading early givesundefined.function greet() {}hoists the whole function, so you can call it above its definition.letandconstare registered but left uninitialized. Reading them before the declaration line throws aReferenceError. The region above the line is the temporal dead zone (TDZ).
This is not trivia: millions of lines of pre-2015 code use var, and reading legacy code means predicting it. Hoisting also explains why let and const were designed with the TDZ — it turns a silent undefined bug into a loud, findable error.
Code exercise · javascript
Run it. The var read gives undefined (name exists, value not assigned yet), and the function call works from above its own definition.
Quiz
Replace `var score` with `let score` in the example. What does the first `console.log(score)` do?
Code exercise · javascript
Run it. Reading `score` before its `let` line is inside the temporal dead zone and throws — the try/catch is only here to show WHICH error. Swap `let` for `var` and rerun: the loud error becomes a silent `undefined`.
Problem
The classic hoisting trick. What does this print, one word: ```javascript var x = 1; function f() { console.log(x); var x = 2; } f(); ```