Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope during compilation.
When your JavaScript runs, the engine first scans your code and registers all the declarations (functions and variables). This makes some things available earlier than you might expect.
Hoisting doesn’t move your code. It just means declarations are known before execution starts. Initial values are not.
var variables are hoisted and set to undefined until the assignment runs.let and const are hoisted too, but they stay in the Temporal Dead Zone (TDZ) until their declaration line executes. Accessing them early throws an error.sayHello(); // ✅ Works: "Hello!"
function sayHello() {
console.log("Hello!");
}
var hoisting (declared early, initialized as undefined)Average 5.0 by 3 learners
console.log(username); // ✅ Defined but undefined
var username = "Aisha";
console.log(username); // "Aisha"
What actually happens under the hood is similar to:
var username; // hoisted as undefined
console.log(username); // undefined
username = "Aisha"; // assignment happens here
console.log(username); // "Aisha"
let / const and the Temporal Dead Zone (TDZ)let and const are hoisted but not initialized. Touching them before their declaration line throws a ReferenceError.
// console.log(score); // ❌ ReferenceError (TDZ)
let score = 10; // leaves the TDZ here
console.log(score); // 10
// console.log(PI); // ❌ ReferenceError (TDZ)
const PI = 3.14; // must be initialized at declaration
console.log(PI); // 3.14
Only the variable name is hoisted, not the function value.
var, the variable is undefined until assignment, so calling it early fails at runtime.let/const, accessing it early is a ReferenceError due to TDZ.// Using var
// greet(); // ❌ TypeError: greet is not a function (greet is undefined)
var greet = function () {
console.log("Hi");
};
greet(); // ✅ "Hi"
// Using let
// wave(); // ❌ ReferenceError (TDZ)
let wave = () => console.log("👋");
wave(); // ✅ "👋"
function declarations: the teacher and the lesson are fully ready—you can call on them immediately.var: the seat exists but has no student yet (undefined) until they walk in.let/const: the seat is reserved but off-limits (TDZ) until the student arrives at that exact moment.const by default; use let when you need to reassign.var in modern code—its hoisting to undefined and function scope can surprise you.