DEV Community

Cover image for "Var vs Let: The Big Confusion Explained!"
Muhammad Burhan Chughtai
Muhammad Burhan Chughtai

Posted on

"Var vs Let: The Big Confusion Explained!"

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.

  1. Loop Example (Per-Iteration New Variable)
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
// Output: 0, 1, 2
Enter fullscreen mode Exit fullscreen mode
  1. 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)
}
Enter fullscreen mode Exit fullscreen mode

" let variables cannot be accessed from outer scopes after their block ends."

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

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 
Enter fullscreen mode Exit fullscreen mode
  1. Var Function Scope Example:
function test() {
  if (true) {
    var x = 10;     // Function scope, NOT block scope
  }
  console.log(x);   // 10 - Accessible everywhere in function
}

Enter fullscreen mode Exit fullscreen mode

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

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)