JavaScript Hoisting and Temporal Dead Zone Explained

šŸ¤” Ever wondered… Why this works: console.log(a) // undefined var a = 10; But this crashes: console.log(b) // ReferenceError let b = 20; Even though both are declared later? šŸ‘‰ This is where most developers think they understand JavaScript… but they don’t. šŸš€ Let’s break it down: Hoisting & Temporal Dead Zone (TDZ) 🧠 Hoisting (What actually happens behind the scenes) JavaScript doesn’t execute your code line by line directly. Before execution, it runs a Memory Creation Phase where: • Variables & functions are registered in memory • Declarations are processed first šŸ‘‰ This is what we call hoisting šŸ“¦ Variable Hoisting With var: • Declaration is hoisted • Initialized with undefined So: • You can access it before declaration • But you won’t get the actual value , since Initialized with undefined in memory creation phase šŸ’” Key insight: Hoisting ≠ moving code It’s about how memory is allocated internally. āš ļø let & const → Temporal Dead Zone (TDZ) Yes — let and const are also hoisted. But… They stay in a Temporal Dead Zone from: šŸ‘‰ start of scope → until declaration line Accessing them early = šŸ’„ ReferenceError šŸ’” Takeaway: TDZ exists to prevent unpredictable bugs caused by premature access. šŸ‘‘ Function Hoisting (VIP behavior) Function Declarations are fully hoisted: āœ” You can call them before declaration But Function Expressions behave differently: • var → undefined • let/const → ReferenceError ⚔ Why this actually matters (not just theory) Understanding hoisting + TDZ helps you: • Avoid silent bugs (undefined issues) • Write predictable, cleaner code • Debug scope-related issues faster • Truly understand how JS engine works šŸ’” Final Thought: Most developers memorize hoisting. Good developers understand execution context. Great developers write code that doesn’t depend on hoisting at all. šŸ“Œ I’ll be sharing more deep dives like this as I learn & build in public. Follow along if you’re into JavaScript internals šŸš€ #JavaScript #FrontendDevelopment #WebDevelopment #Hoisting #TDZ #LearnJavaScript #CodingTips #BuildInPublic #100DaysOfCode

  • code snippet.

To view or add a comment, sign in

Explore content categories