Hoisting is JavaScript’s default behavior of moving declarations to the top of their scope before code execution. This means variables and functions can be referenced before they are declared, but how they behave depends on the type of declaration.
1️⃣ Hoisting with var
- Variables declared with
varare hoisted and initialized withundefined. - You can reference the variable before its declaration, but its value is
undefineduntil the assignment line is reached.
console.log(a); // undefined
var a = 10;
console.log(a); // 10
Explanation:
The JS engine internally does this:
var a; // declaration hoisted
console.log(a); // undefined
a = 10; // assignment remains in place
console.log(a); // 10
2️⃣ Hoisting with let
- Variables declared with
letare hoisted but not initialized. - Accessing them before declaration causes a ReferenceError due to the temporal dead zone (TDZ).
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 20;
Explanation:let and const are in a TDZ from the start of the scope until the declaration line.
3️⃣ Hoisting with const
- Works like
let— hoisted but not initialized. - Must be initialized at the time of declaration.
- Accessing before declaration or not initializing will throw an error.
console.log(c); // ReferenceError
const c = 30;
const d; // SyntaxError: Missing initializer in const declaration
4️⃣ Function Hoisting
Function Declarations
- Fully hoisted — you can call them before they appear in code.
sayHi(); // "Hi!"
function sayHi() {
console.log("Hi!");
}
Function Expressions
- Hoisted only as variables:
console.log(sayHello); // undefined
var sayHello = function() {
console.log("Hello");
};
✅ Summary Table
| Declaration | Hoisted? | Initialized? | Access before declaration |
|---|---|---|---|
var |
Yes | undefined |
Yes, returns undefined |
let |
Yes | No | No, ReferenceError (TDZ) |
const |
Yes | No | No, ReferenceError (TDZ) |
| Function Declaration | Yes | Yes | Yes, can call early |
| Function Expression | Yes (var) | No | No, undefined if var; TDZ if let/const |
In short:
Hoisting moves declarations to the top.
vargets initialized withundefined, whileletandconstare hoisted but stay uninitialized until the line is reached (TDZ). Functions are fully hoisted if declared normally.