12

so I've got a warning in my JS compiler but could you explain to me if this will actually affect the way my code will execute?

for (x = 0; x < levels.length; x++) {
    var level = levels[x];
    var candlesOnLevel = $.grep(relevantCandles, function(candles, index) {
        return parseInt($(candles).css("top").replace(/px/, "")) === level;
    });
}
Tushar
  • 85,780
  • 21
  • 159
  • 179
Miguel Boland
  • 131
  • 1
  • 4

2 Answers2

9

Why are you getting the warning

As @RGraham mentioned in comments, the js compiler is assuming that second parameter to $.grep() is a callback function and is being executed asynchronously(atleast this is what it look like syntactically). However thats not true because the second function is in-fact a filter function. See the API docs

One usually get the warning Mutable Variable is accessible from closure when using an async function inside a for loop. Thats because the entire for loop has one scope. That means on each iteration, you would end up capturing the same variable. So the callback will get the wrong ids, because level(being mutable) will be changed before the callback is called. Fortunately, thats not the case you are dealing with(because $.grep is not async) :)

...could you explain to me if this will actually affect the way my code will execute?

No, such warning wont affect the outcome of your code.

You can simply ignore the warning but if you still want to avoid this, you can put the contents inside a closure.

for (x = 0; x < levels.length; x++) {
   (function(){
       var level = levels[x];
       var candlesOnLevel = $.grep(relevantCandles, function(candles, index) {
           return parseInt($(candles).css("top").replace(/px/, "")) === level;
       });
   })();
}
nalinc
  • 7,375
  • 24
  • 33
4

It warns you that level can be modified before that grep "callback" gets to it - of course, the IDE doesn't know that $.grep doesn't take a callback, but a filter function. (Note that async functions taking a callback usually have the same signature)

If it were an asynchronous callback function, then when reading the value of the level, it would find the value last set there - in the last iteration of the foor loop, and not the value present when you dispatched the call, which would cause problems - hence the (mind you, usually very useful) warning.

doldt
  • 4,466
  • 3
  • 21
  • 36