Understanding JavaScript Hoisting and the Temporal Dead Zone

Day 3: JavaScript Hoisting — Magic or Logic? Yesterday, we learned that JavaScript creates memory for variables before it executes the code. Today, let’s see the most famous (and sometimes confusing) result of that: Hoisting. What is Hoisting? Hoisting is a behavior where you can access variables and functions even before they are initialized in your code without getting an error. Wait... why didn't it crash? 🤔 If you try this in other languages, it might throw an error. But in JS: During Memory Phase: JS saw var x and gave it the value undefined. It saw the function getName and stored its entire code. During Execution Phase: When it hits console.log(x), it looks at memory and finds undefined. When it hits getName(), it finds the function and runs it! ⚠️ The "Let & Const" Trap Does hoisting work for let and const? Yes, but with a catch! They are hoisted, but they are kept in a "Temporal Dead Zone". If you try to access them before the line where they are defined, JS will throw a ReferenceError. Pro Tip: Always define your variables at the top of your scope to avoid "Hoisting bugs," even though JS "magically" handles them for you. Crucial Takeaway: Hoisting isn't code physically moving to the top; it’s just the JS Engine reading your "ingredients" before "cooking" (Phase 1 vs Phase 2). Did you know about the Temporal Dead Zone? Let me know in the comments! #JavaScript #WebDev #100DaysOfCode #Hoisting #CodingTips #FrontendDeveloper

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories