I've been starting to use IIFEs within for-loops, like so:
var currentItem = 2; // IIFE helps prevent variable collision
for(var i = 0; myArray.length < i; i++){
(function(){
var currentItem = myArray[i];
// do stuff
})();
}
The main reason I've been doing this is to give some scope to the for-loop, so the variables don't escape this scope. Are there any negative effects/performance hits of doing so? And if so, what is the extent of their harm? Thanks!
1 Answer 1
Yes there is a performance cost in wrapping the body of a for statement into an anonymous function. The problem is the cost of creating a new function object for each iteration. That is, for each iteration a new function object is created with its own scope.
Performance comparison named vs anonymous function This is a small comparison between named function and function declaration which may help you to understand the impact over the performance of your code. Note, in your case, the problem is not the anonymous function, but rather the cost of creating the function object.
ES6
I understand, you are trying to scope your variable to the for. I would suggest another solution to achieve this. If you can, try to use let keyword from ES6.
The let keyword has been introduced to overcome all of var's defects, such as this one. let allows you to declares variable that are limited in scope to the for block.
letallows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
3 Comments
let sounds pretty great! Can't wait to see it pick up more traction as far as browser support goes!
.forEach()?currentItemandi) are visible after the loop, so what?i.