Clean β’ Professional
Hoisting is JavaScriptβs behavior of moving declarations to the top of their scope during the compilation phase, before the code runs.
However, initializations are not hoisted, and the behavior differs for var, let, const, and functions.
var variables are hoisted and initialized as undefined.let and const are hoisted but not initialized β they stay in the Temporal Dead Zone (TDZ) until their declaration line.var Hoistingvar x is hoisted to the top, but its value (5) is assigned later.
console.log(x); // undefined (hoisted, but not initialized)
var x = 5;
console.log(x); // 5
Itβs as if the code runs like this:
var x;
console.log(x); // undefined
x = 5;
console.log(x); // 5
let / const Hoisting (Temporal Dead Zone)let and const are hoisted but remain uninitialized in the Temporal Dead Zone (TDZ) β accessing them before declaration throws an error.
// console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 10;
console.log(y); // 10
Function declarations are fully hoisted β you can call them before their definition.
myFunc(); // Works: "Hello!"
function myFunc() {
console.log("Hello!");
}
Here, only the var declaration is hoisted (as undefined), not the assigned function.
Thatβs why calling it before definition causes an error.
// myFunc(); // Error: myFunc is not a function
var myFunc = function() {
console.log("Not hoisted!");
};
myFunc(); // "Not hoisted!"