JavaScript Hoisting

JavaScript Tutorial

JavaScript Hoisting

In JavaScript Hoisting default behavior of moving variable and function declarations to the top of their scope before execution.

This means you can use variables and functions before declaring them (but with rules).


 1️⃣ Hoisting with var

Variables declared with var are hoisted but initialized as undefined.



 2️⃣ Hoisting with let and const

let and const are hoisted but NOT initialized.
Accessing them before declaration causes an error because they are in the Temporal Dead Zone (TDZ).


 3️⃣ Function Hoisting

✔ Function Declarations are fully hoisted:


 


❌ Function Expressions are NOT fully hoisted:


 


⚠️ Arrow Functions behave like function expressions:


 


🧠 Summary Table

Declaration Type Hoisted? Initialized? Can Use Before Declaration?
var ✔ Yes undefined ⚠ Yes (but undefined)
let ✔ Yes ❌ No (TDZ) ❌ No
const ✔ Yes ❌ No (TDZ) ❌ No
Function Declaration ✔ Yes ✔ Yes ✔ Yes
Function Expression ✔ Yes ❌ No ❌ No
Arrow Function ✔ Yes ❌ No ❌ No

🎯 Best Practices

✔ Use let and const to avoid confusion
✔ Declare variables at the top of their scope
✔ Avoid relying on hoisting behavior in real projects

You may also like...