'Var vs Let: The Big Confusion Explained!'
Source: Dev.to

It’s a clear thought about “Let” and “Var” concept.
Let
You’ve probably heard that let is block‑scoped. Let’s see exactly how it works in loops, functions, and 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)
}
letvariables 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[i] = () => console.log(i); // each i has its own closure
}
closures[0](); // 0
closures[1](); // 1
closures[2](); // 2
}
Closure is a function that remembers the outer function’s scope variables.
Var
The biggest source of confusion with var is its behavior in loops.
Loop Example
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// Output: 3, 3, 3
Step‑by‑step:
- 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 three timeouts run after the loop, so console.log(i) prints 3.
Function Scope Example
function test() {
if (true) {
var x = 10; // Function scope, NOT block scope
}
console.log(x); // 10 – accessible everywhere in the 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 for each block.
Helpful video demo: https://www.youtube.com/watch?v=1mgLWu69ijU