JS Mutable variable available from closure

so I have a warning in my JS compiler, but could you explain to me whether this will really affect the way my code?

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; }); } 
+8
javascript jquery
source share
2 answers

Why do you get a warning

As @RGraham noted in the comments, the js compiler assumes that the second parameter $.grep() is a callback function and executes asynchronously (at least this is syntactic). However, this is not true because the second function is actually a filter function. See API docs

A warning is usually issued Mutable Variable is accessible from closure when using the async function inside a for loop. That is because the whole for loop has one area. This means that at each iteration, you should get the same variable. Thus, the callback will receive the wrong identifiers, because level (being mutable) will be changed before the callback is called. Fortunately, this is not the case you are dealing with (because $ .grep is not async) :)

... could you explain to me whether this will really affect my code to execute?

No, such a warning will not affect the result of your code.

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

 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; }); })(); } 
+5
source share

It warns you that level can be changed before this grep accesses it - of course, the IDE does not know that $.grep does not perform a callback, but a filter function. (Note that asynchronous callback functions usually have the same signature)

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

+4
source share

All Articles