If youβre learning JavaScript, you must understand how var, let, and const behave with scope and hoisting. Letβs explore with simple examples π
β Variable Declarations
var a = 10; // global/function scope let b = 20; // block scope const c = 30; // block scope console.log(a, b, c); // 10 20 30 a = 100; // valid b = 200; // valid // c = 300; // β invalid console.log(a, b, c); // 100 200 30 π Key Takeaways:
-
varβ function/global scoped π» -
letβ block scoped π -
constβ block scoped, no reassignment allowed π«
β‘ Hoisting Example
console.log(x); // undefined var x = 50; console.log(x); // 50 π var gets hoisted as undefined until assigned.
π« Temporal Dead Zone (TDZ)
console.log(y); // β ReferenceError let y = 10; Even though let and const are hoisted, they live in the Temporal Dead Zone until declared.
π Recap
β
Prefer let & const in modern JavaScript.
β
Avoid var unless you know the quirks.
β
Understand hoisting to debug smarter.
π‘ Whatβs your biggest confusion about scope & hoisting? Letβs discuss in the comments π
Top comments (0)