var vs let: Execution Context and Hoisting in JavaScript

JavaScript Internals: What Actually Happens with var vs let? Most explanations stop at: • var is function-scoped • let is block-scoped But internally, the difference is deeper. 🔹 Execution Context Creation Phase When JS runs, it creates an Execution Context with: 1️⃣ Variable Environment 2️⃣ Lexical Environment 🔴 How var Works Internally • Stored inside the Variable Environment • Hoisted and initialized with undefined • In global scope, attached to the global object (window in browser) Example: console.log(a); // undefined var a = 10; During memory phase: var a = undefined; 🟢 How let Works Internally • Stored inside the Lexical Environment • Hoisted but NOT initialized • Placed inside the Temporal Dead Zone (TDZ) • Not attached to the global object Example: console.log(b); // ReferenceError let b = 20; Memory is allocated, but access before initialization throws error. 🔥 Key Engine-Level Difference var → Accessible before assignment (value: undefined) → Attached to global object → No block scope let → Hoisted but inaccessible (TDZ) → Block scoped → Not part of global object Understanding this helps in: • Avoiding accidental globals • Preventing hoisting bugs • Writing predictable async code • Debugging production issues JavaScript behavior is not “magic” — it’s execution context design. #JavaScript #FrontendDevelopment #ReactNative #WebDevelopment #ProgrammingInternals

To view or add a comment, sign in

Explore content categories