🔰hoisting
lifts identifiers to top of scope.
hoists identifiers to the top of a scope (at compile-time)
var hoisting - declaration hoisted, value initialized to "undefined".
let/const/class hoisting - declaration hoisted, value "uninitialized"❗️
const requires initialization - must have with initial value❗️
function hoisting - declaration hoisted, value initialized to a function.
lexical declaration ( let / const / class )
is "uninitialized" first (at compile-time).
then initialized to its initial value (when execution reaches its declaration at runtime)❗
there's a temporal dead zone between these two states, be aware❗
hoisting priority
function declaration is hoisted first (function hoisting).
declared variable cannot be accessed in the TDZ.
replit:hoisting & TDZ
const { log } = console;
function hi() {
var x = "Hello";
// block scope
{
// ----------------------------------------------------------------
// ⭐️ the compiler WON'T check if `x` is referenced in the TDZ
// at compile-time, but will cause run-time error when running❗
// ----------------------------------------------------------------
x = "Howdy"; // ╮
// ⭐️ Temporal Dead Zone (TDZ) for `x`
// ╯ (can't access `x` in this zone❗)
let x = "Hi"; // ⭐️ `x` declared here❗
log(x);
}
}
log('hello'); // ✅ 'hello' (this is OK.)
hi(); // ⛔ run-time error
//
// ⛔ ReferenceError:
// Cannot access 'x' before initialization
// (note: this is a runtime error❗)Last updated
Was this helpful?