It's a clear thought about "Let" and "Var" concept
Let:
You have mostly heard that let it's a blocked scope, so Yes but question is that, How exactly does it work. Mostly, developrs get stuck here - their mind goes blank.
So, Don't worry I will show you exactly let creates new variables per block, with simple example in loops, functions , and in closures.
- Loop Example (Per-Iteration New Variable)
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// Output: 0, 1, 2
- Function Example (Block Shadowing)
function test() {
let x = 10; // Outer x
if (true) {
let x = 20; // New x (shadows outer x)
console.log(x); // 20
}
console.log(x); // 10 (outer x unchanged)
}
" let variables cannot be accessed from outer scopes after their block ends."
- Closure Example (Each Block Independent)
function createClosures() {
const closures = [];
for (let i = 0; i < 3; i++) {
closures.push(() => console.log(i)); // Har i ka apna closure
}
closures[0](); // 0
closures[1](); // 1
closures[2](); // 2
}
Closure it's a function that remember the outer function scope's variable.
Var:
Now let's clear up the biggest confusion about var—why when use in loop and give condition " <= 3 " then it prints 3, 3, 3 in loops and drives everyone crazy!
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// Output: 3, 3, 3
Step-by-Step What Happens:
Iteration 1: var i = 0 ← ONE variable created
Iteration 2: i = 1 ← Same variable, value CHANGED
Iteration 3: i = 2 ← Same variable, value CHANGED
Loop ends: i = 3 ← Final value
All 3 timeouts run → console.log(i) = 3
- Var Function Scope Example:
function test() {
if (true) {
var x = 10; // Function scope, NOT block scope
}
console.log(x); // 10 - Accessible everywhere in function
}
Var vs Let - The Real Difference
| Situation | var | let |
| ------------------- | ------------------ | ---------------------- |
| Loop + setTimeout | 3, 3, 3 | 0, 1, 2 |
| Inside { if } block | Accessible outside | ReferenceError |
| Same name in blocks | Same variable | New variable each time |
| Scope | Function/Global | Block only |
Final In-Short:
var = One variable that changes value
let = New variable every block
I've attached a helpful video demo: https://www.youtube.com/watch?v=1mgLWu69ijU
Top comments (0)