Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Mutable Variable is accessible from closure [duplicate]

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;
    });
}
like image 619
Miguel Boland Avatar asked Jul 01 '15 10:07

Miguel Boland


People also ask

Is closure unique to JavaScript?

Closures are a very powerful yet underused feature unique to of JavaScript (and other ECMAScript languages).

What kind of access closure variable have?

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.

What is closure variable in JavaScript?

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.

Can we have nested function in JavaScript?

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).


1 Answers

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;
       });
   })();
}
like image 63
nalinc Avatar answered Sep 28 '22 07:09

nalinc