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;
});
}
Closures are a very powerful yet underused feature unique to of JavaScript (and other ECMAScript languages).
The closure has three scope chains: it has access to its own scope — variables defined between its curly brackets. it has access to the outer function's variables. it has access to the global variables.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to).
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;
});
})();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With