This is because JavaScript has only a function area , not a block area. Therefore, every variable you declare in a loop is in the function area, and every closure you create has access to the same variable.
So the only way to create a new scope is to call a function, and this is what
(function(i){}(i))
does.
Note that your example skips the important part: the immediate function should return another function that will be the click handler:
someArray[i].onclick = (function(i){ return function() { } }(i));
The immediate function is nothing special. It is somehow embedding a function definition and calling a function. You can replace it with a regular function call:
function getClickHandler(i) { return function() { } } for(var i=0; i < someArray.length; i++){ someArray[i].onclick = getClickHandler(i); }
Felix kling
source share