-
Notifications
You must be signed in to change notification settings - Fork 150
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
vars in for loop declarations should be declared in upper-scope. #145
Comments
Vars should be hoisted, then converted to let function logTheLengthOfTheArrayForEachElementInTheArrayAsync() {
const messages = [0, 1, 2];
let i;
for (i = 0; i < messages.length; i++) {
function logMessage() {
console.log(i)
}
setTimeout(logMessage)
}
}
logTheLengthOfTheArrayForEachElementInTheArrayAsync(); |
Thanks for reporting. The problem is that it's no way to tell whether the function logMessage is invoked synchronously or asynchronously. For example the following code works fine with either for (let i=0; i<10; i++) {
messages.forEach(function(msg){ console.log(msg + i); });
} So to solve it we'll have to detect it in a more generic fashion:
In which case we'd leave the variable as @graingert Could you come up with a more real-life examples? The current one looks more like the code was buggy to start with. |
Rather than leaving the variable as var you could just manually move it to
|
As I said, currently the That would be a feature to be implemented separately from fixing this bug, but I'm not really sure it's a good thing to do. This kind of code is probably better to be manually rewritten - with the help of warnings #136 it should soon become simpler to do so. |
Instead of moving it you could wrap the for loop in a new scope. {
let i;
for (i in ...){}
} On 7 Jul 2016 14:06, "Rene Saarsoo" [email protected] wrote:
|
Introducing a plain block would be an even stranger code. And I would still consider it as "moving" the declaration. I would rather declare the variable in original parent block. But the main priority currently is to not do a transform that could introduce a bug. Properly transforming all the edge cases is not the main priority. |
prints:
but:
prints:
0
1
2
The text was updated successfully, but these errors were encountered: