Creating functions in a loop


#1

I have an warning - about creating a functions within a loop:

for (var j = 0; j < some.length; ++j) {

array[j] = SOMETHING;

array[j].sort(function (a, b){return a.distance-b.distance;});

}

can the parser be made to handle this?


#2

I ran into the same problem. The simplest solution would just be to define it outside of the loop.

var customSorter = function(a, b) {
     // sorter stuff
};

for (var i=0; i<a.length; i++) {
     a[i].sort(customSorter);
}

Sometimes, you might need the loop variables. In this case, then you need to create a function that returns another function.

var customSorter = function(elem) {
    return function(a, b) {
         // you can use elem here
    };
};

for (var i=0; i<a.length; i++) {
     a[i].sort(customSorter(i));
}

#3

great - thank you - that fixed it up :smile:


#4

Yeah, the warning there is part of JSHint, just mentioning that since creating functions is slow, you usually want to do it outside of loops.