There is no block scope in JavaScript, so unlike in other languages, loops don't have scope. Fortunately, there is a really simple solution to that: just put a function inside of the loop that will create JavaScript functional scope:
for (var i=0; i<=numberOfItems; i++){
(function(i, d){
//do something with d
}(i, d[i]));
}
The more elegant way of course is to use the jQuery's $.each() function, which offers the "functional closure" by default. It can be used like this:
$.each(data, function(i, d){
//do something with d
});
Of course, we could make the first example to follow the same pattenr like the jQuery "each" function, so the code would look some like this:
var forEach = function(d, f){
var l = d.length,
for (var i=0; i<=l; i++){
f(i, d[i]);
}
};