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 โ undefinedExecution 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 escapedvar 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 hereThe engine knows the variable exists but forbids access until itโs initialized.
Block Scope (Finally!)
if (true) {
let score = 100;
}
console.log(score); // โ ReferenceErrorlet respects block boundaries, making code safer and cleaner.
๐ const โ The Strict One
const pi = 3.14;
pi = 3.14159; // โ TypeErrorRules of const
- Must be initialized immediately
- Cannot be reassigned
- Blockโscoped
- Hoisted (but stays in TDZ until initialization)
const x; // โ SyntaxErrorThe Famous const + Object Confusion
const user = { name: "Hardeep" };
user.name = "Singh"; // โ
Allowed
user = {}; // โ Not allowedconst 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.