Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
JavaScript

JavaScript: Why a Closure Inside a Loop Captures the Same Value on Every Iteration

- 06.09.26 - ErcanOPAK

⚡ Every Callback in Your Loop Is Using the Same Final Value, Not Its Own

A loop creates a callback for each iteration – a click handler, a `setTimeout`, a promise `.then()` – expecting each one to remember the value of the loop variable at the moment it was created, but every single callback ends up using the SAME final value instead, because of how `var` scoping and closures interact.

🔎 The Problem

for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('"'"'click'"'"', function () {
        console.log('"'"'You clicked button number: '"'"' + i);
    });
}

// Click ANY button, and the console always logs the SAME number -
// buttons.length (one past the last valid index) - because `var i` is
// scoped to the whole function, not to each loop iteration, so every
// closure captured a reference to the same `i`, and by the time any
// click actually happens, the loop has already finished and `i` holds
// its final value.

✅ Fix: Use `let` Instead of `var`

  • Simply changing `var i` to `let i` fixes it completely – `let` creates a NEW binding for `i` on every iteration of the loop, so each closure captures its own separate value instead of sharing one.
  • This is one of the clearest practical reasons `let`/`const` replaced `var` as the default choice in modern JavaScript – the per-iteration scoping isn’t a stylistic preference, it changes actual program behavior in exactly this situation.

⚠️ If You’re Stuck With `var` (Older Codebases)

  • Wrap the loop body in an IIFE (immediately-invoked function expression) that takes `i` as a parameter – `(function (capturedI) { … })(i);` – which manually creates the fresh binding `let` gives you for free.
  • `Array.prototype.forEach` sidesteps the problem entirely, since each callback invocation naturally gets its own parameter value rather than sharing a loop variable: `buttons.forEach(function (btn, i) { … });`.

A closure doesn’t remember what a variable WAS – it remembers the variable itself, and if every iteration shares one variable, every closure shares one memory.

— JavaScript Tip

Related posts:

JavaScript: Preventing Memory Leaks with WeakMap and WeakSet

JavaScript: Preventing Memory Leaks with WeakMap and WeakSet

JavaScript Proxy and Reflect: Metaprogramming Power for Modern Apps

JavaScript Proxy and Reflect: Metaprogramming Power for Modern Apps

AJAX “POST Suddenly Fails” — The Missing Content-Type Header

AJAX “POST Suddenly Fails” — The Missing Content-Type Header

Views: 9

Post navigation

Windows 11: Fix Bluetooth Devices That Disconnect Every Few Minutes
WordPress: Fix a Plugin Update That Breaks the Site With No Error Message

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com