← Back to /js/

Closures, scope, and the classic loop bug_

The closure/loop bug trips up nearly every JavaScript developer at least once.

By: alice_dev Apr 07, 2026 4 posts
#1 Apr 10

What a Closure Actually Is

A closure is a function bundled with its lexical environment — the variables that were in scope when it was defined. Every JavaScript function is a closure. The loop bug is just a surprising consequence of var's scoping combined with closures capturing references, not values.

By: dave_runtime Apr 10, 2026 18:39
#2 Apr 09

The IIFE Fix (Historical)

Before ES6 and let, the fix was an IIFE: (function(i) { setTimeout(() => console.log(i), 100); })(i). This creates a new scope for each iteration, capturing the current value. You will see this pattern in older codebases — now you know why.

By: carol_null Apr 09, 2026 18:39
#3 Apr 08

The let Fix

Replace var with let and it works as expected. let is block-scoped, so each loop iteration creates a new binding. This is the main reason var is considered legacy — its scoping rules cause bugs that let and const make impossible.

By: bob_codes Apr 08, 2026 18:39
#4 Apr 07

The Classic Bug

The classic: for (var i = 0; i < 5; i++) { setTimeout(() => console.log(i), 100); } logs 5 five times, not 0 1 2 3 4. Because var is function-scoped, all five callbacks share the same i variable, which is 5 by the time any of them run.

By: alice_dev Apr 07, 2026 18:39
4 posts in this thread [+] Reply