Skip to main content
xenoveritas.org

Main navigation

  • Categories
  • Home
  • Links
  • Name Generator
  • Scramble
User account menu
  • Log in

Breadcrumb

  1. Home

JavaScript

By Xenoveritas, 30 June, 2015

JavaScript Closures and Loops

Topics
Web
JavaScript

JavaScript closures can be kind of weird. The way a closure works within a loop is a fairly common "gotcha" because it doesn't work in the way that it intuitively feels like it should.

Take the following block of code:

for (var i = 0; i < 5; i++) {
    var button = document.createElement("button");
    button.innerHTML = "Button #" + (i + 1);
    button.onclick = function() {
        alert("You clicked on " + button.innerHTML + "!");
    };
    document.body.appendChild(button);
    document.body.appendChild(document.createElement('br'));
}

What does that do? Read More to find out.

JavaScript

Current Games

I'm currently playing:

  • Final Fantasy XIV: Endwalker

I intend to maybe get around to finishing:

  • Literally anything else

Video Games Section

Thought for the Moment

I never have thoughts any more.

Old Thoughts

Has the LHC Destroyed the Earth?

  • Create new account
  • Reset your password
RSS feed
Powered by Drupal