Your JavaScript Loop (oh the horror)

var funcs = {};

for (var i = 0; i < 3; i++) {
    funcs[i] = function() {
        document.write("<p>My value: " + i + "</p>");
    };
}

for (var j = 0; j < 3; j++) {
    funcs[j]();
}

Looks like sane code to me. Well, except for JavaScript's predilection/requirement for anonymous functions. Boring, but sane. The output?:

My value: 3

My value: 3

My value: 3

Really. WTF?! No, you can't do it that way. You have to do this:

var funcs = [];

function createfunc(i) {
    return function() { document.write("<p>My value: " + i + "</p>"); };
}

for (var i = 0; i < 3; i++) {
    funcs[i] = createfunc(i);
}

for (var j = 0; j < 3; j++) {
    funcs[j]();
}

Which produces the output you expected the first time:

My value: 0

My value: 1

My value: 2

Fans of JavaScript wonder why I complain about the language. It's not assigning the variable value when it's used. That's not expected behaviour in any other programming language, and wouldn't be considered good behaviour by anyone. Ugh.

Courtesy of the ever-helpful Stack Overflow, which has saved me from insanity with this language more than once: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example.