Closures:

1. First Loop (with differentScope
function):
for(var i=1;i<=5;i++){
const differentScope = (i)=>{
setTimeout(()=>{
console.log(i)
},i*1000);
}
differentScope(i);
}
Output: 1 2 3 4 5
(each number printed at 1-second intervals)
Explanation:
We're using
var
for the loop variablei
Inside each iteration, we create a function
differentScope
that takesi
as a parameterWe immediately call
differentScope(i)
with the current value ofi
Because
i
is passed as a parameter to the function, it creates a new scope for each iterationEach setTimeout gets its own copy of
i
from its scopeThis works correctly, printing 1 through 5 at 1-second intervals
2. Second Loop (plain var
with setTimeout):
for(var i=1;i<=5;i++){
setTimeout(()=>{
console.log(i)
},i*1000);
}
Output: 6 6 6 6 6
(each 6 printed at 1-second intervals)
Explanation:
We're using
var
which is function-scoped, not block-scopedThe loop completes before any setTimeout callback runs
By the time the callbacks execute,
i
has already reached 6 (the loop stops wheni
becomes 6)All callbacks share the same
i
variable, which is now 6The delays are still 1s, 2s, etc. because
i*1000
is evaluated during the loop iteration
3. Third Loop (using let
):
for(let i=1;i<=5;i++){
setTimeout(()=>{
console.log(i)
},i*1000);
}
Output: 1 2 3 4 5
(each number printed at 1-second intervals)
Explanation:
We're using
let
which is block-scopedIn a
for
loop withlet
, a new binding is created for each iterationEach setTimeout callback gets its own
i
from its respective iterationThis works correctly, printing 1 through 5 at 1-second intervals
Key Differences:
The first loop works because we're passing
i
to a function, creating a new scope for each iteration.The second loop fails because
var
doesn't create a new binding for each iteration, and all callbacks share the samei
.The third loop works because
let
creates a new binding for each iteration in afor
loop.
This demonstrates why let
is generally preferred in modern JavaScript for loop variables, especially when dealing with asynchronous operations inside loops.
Subscribe to my newsletter
Read articles from Vishal Pandey directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
