Don't make functions within a loop

Thijs Koerselman picture Thijs Koerselman · Apr 25, 2012 · Viewed 70.8k times · Source

What would be the correct way to solve the jslint error in this case? I'm adding a getter function to an object which uses this. I don't know how to do this without creating the function inside the loop.

for (var i = 0; i<processorList.length; ++i) {
   result[i] = {
       processor_: timestampsToDateTime(processorList[i]),
       name_: processorList[i].processorName,
       getLabel: function() { // TODO solve function in loop.
            return this.name_;
       }
   };
}

Answer

Rob W picture Rob W · Apr 25, 2012

Move the function outside the loop:

function dummy() {
    return this.name_;
}
// Or: var dummy = function() {return this.name;};
for (var i = 0; i<processorList.length; ++i) {
   result[i] = {
       processor_: timestampsToDateTime(processorList[i]),
       name_: processorList[i].processorName,
       getLabel: dummy
   };
}

... Or just ignore the message by using the loopfunc option at the top of the file:

/*jshint loopfunc:true */