'Var vs Let: The Big Confusion Explained!'

Published: (February 7, 2026 at 05:43 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

Cover image for

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)
}

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[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:

  1. Iteration 1: var i = 0 → one variable created.
  2. Iteration 2: i = 1 → same variable, value changed.
  3. Iteration 3: i = 2 → same variable, value changed.
  4. 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

Situationvarlet
Loop + setTimeout3, 3, 30, 1, 2
Inside { if } blockAccessible outsideReferenceError
Same name in blocksSame variableNew variable each time
ScopeFunction/GlobalBlock 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

0 views
Back to Blog

Related posts

Read more »

Hello World

Hello I am a new web developer, I am looking for new ways to improve as a web developer. If we have any problems connecting what we've learned please contact me...

JS Tips — A JavaScript Tip a Day

!pichttps://media2.dev.to/dynamic/image/width=256,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farti...