Play Home Contribute GitHub Join Us Discourse Staff Members GitHub Contribution Guides Team

Creating functions in a loop


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?


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++) {

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++) {


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


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.