JavaScript에서 VAR, LET, & CONST
Source: Dev.to
🧠 How JavaScript Runs Your Code (Very Important)
JavaScript doesn’t execute your code line‑by‑line immediately.
It first prepares everything, then runs it.
Memory Creation Phase
The JS engine:
- Scans the entire code
- Allocates memory for variables & functions
- Does not assign actual values yet
Execution Phase
- Executes code line by line
- Assigns values
- Runs functions
All of this happens inside an Execution Context.
🧪 var — The OG Troublemaker
console.log(a);
var a = 10;
Result: undefined (not an error) because var is hoisted and initialized with undefined.
Behind the scenes
Memory Phase
a → undefined
Execution Phase
console.log(a); // undefined
a = 10;
Key takeaways about var
- ✅ Hoisted
- ✅ Initialized with
undefined - ❌ Not block‑scoped (function‑scoped)
- ❌ Can be redeclared
- ❌ Easy to mess up
var Does Not Respect Block Scope
if (true) {
var secret = "I should not escape";
}
console.log(secret); // 😱 It escaped
var ignores {} blocks, which caused many real‑world bugs.
🧠 Enter let — The Responsible One
console.log(b);
let b = 20;
Error: ReferenceError: Cannot access 'b' before initialization
Temporal Dead Zone (TDZ) — Explained Simply
TDZ is the time between memory allocation and variable initialization.
Memory Phase
b →
Execution Phase
console.log(b); // ❌ TDZ error
b = 20; // TDZ ends here
The engine knows the variable exists but forbids access until it’s initialized.
Block Scope (Finally!)
if (true) {
let score = 100;
}
console.log(score); // ❌ ReferenceError
let respects block boundaries, making code safer and cleaner.
🔒 const — The Strict One
const pi = 3.14;
pi = 3.14159; // ❌ TypeError
Rules of const
- Must be initialized immediately
- Cannot be reassigned
- Block‑scoped
- Hoisted (but stays in TDZ until initialization)
const x; // ❌ SyntaxError
The Famous const + Object Confusion
const user = { name: "Hardeep" };
user.name = "Singh"; // ✅ Allowed
user = {}; // ❌ Not allowed
const fixes the reference, not the object’s contents—think of a fixed address with movable furniture inside.
📊 Quick Comparison Table
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisted | Yes | Yes | Yes |
| Initialized on hoisting | undefined | ❌ TDZ | ❌ TDZ |
| Redeclare | ✅ | ❌ | ❌ |
| Reassign | ✅ | ✅ | ❌ |
| Recommended today | ❌ No | ✅ Yes | ✅ Yes |
🧠 Behind the Scenes (Slightly Nerdy)
- Variable Environment → used by
var - Lexical Environment → used by
let&const
This is why var can leak out of blocks while let and const do not.
🚀 Best Practices (Learned the Hard Way)
- ✅ Use
constby default - ✅ Use
letonly when reassignment is required - ❌ Avoid
varunless maintaining legacy code
If JavaScript were designed today, var probably wouldn’t exist.
🎯 Final Thoughts
var→ risky and outdatedlet→ safe and flexibleconst→ safest and preferred
JavaScript isn’t weird; we just finally understand how it works.