Before Dina runs a single line, the open house readies every room: what is in a var, function, let, const or class room before its own line runs? Then the…
Hoisting explains mysterious undefined bugs and the "Cannot access before initialization" error that often stops beginners. It is also why let/const are safer than var: a wrong order shows up at once as an error instead of quietly becoming undefined.
Two phases: every name is made first, then the lines run
var does not exist before its declaration It exists from the creation phase on, holding undefined. The code carries on with undefined and no error, undefined + 1 becomes NaN. Use let/const so a wrong order shows up as an error at once.const fn = () => {} is a plain const holding a function, so it follows the TDZ. Only function fn() {} is made whole in the creation phase. Call it after its line, or write it as a function declaration.class before its declaration A class is made like let: it exists, but stays in the TDZ until the class Foo {} line runs. new Foo() before that is a ReferenceError. Put the class above the code that uses it.var fn = function () {} called first gives a TypeError The name exists (a var holding undefined), so what gets called is undefined: "fn is not a function". Move the call below that line, or write it as a function declaration.console.log(x) runs It prints undefined, not an error: room x has existed since the creation phase, but the line that puts the 1 in has not run.let x = 2 up In the first order you hit a ReferenceError (the TDZ). Build your program, move let x up with the arrow, run it again: now it prints 2.fn() before var fn = function () {} The "trap" situation. It gives the TypeError "fn is not a function", not a ReferenceError: the room exists, it still holds undefined.fn is called after let x, so it prints 2. Move console.log(fn()) above let x, run it again: a ReferenceError.