JavaScript Hoisting

βœ… JavaScript Hoisting

Hoisting is JavaScript’s 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

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *