DEV Community

Usama
Usama

Posted on

πŸ”₯ Mastering JavaScript Variables & Hoisting πŸš€

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
Enter fullscreen mode Exit fullscreen mode

πŸ”‘ 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
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ var gets hoisted as undefined until assigned.


🚫 Temporal Dead Zone (TDZ)

console.log(y); // ❌ ReferenceError
let y = 10;
Enter fullscreen mode Exit fullscreen mode

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)