Bugs
JavaScript Closure Bugs: The Classic Loop Variable Problem
JavaScript closures capture variables by reference, not by value. In loops using var, all closures share the same variable, leading to classic bugs.
❌ Classic Closure Bug with var
for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i); // Prints '5' five times!
}, i * 100);
}✅ Fixed with let
for (let i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i); // Prints 0, 1, 2, 3, 4 correctly
}, i * 100);
}💡
Pro tip: let creates a new binding for each loop iteration. Each closure captures its own independent copy of i. Always prefer let/const over var.
Paste this code into LearnCodeGuide
Detect JavaScript vulnerabilities and bugs automatically with AI-powered analysis.
Analyze JavaScript Code →