Consider the following code:
for (var x = 0; x < 10; x++) { /* do awesome stuff. 10 times! */ }
console.log(x);
x is still printed in the console.
This gives me warnings in JSHint, because a couple of lines further I do another loop, redeclaring x:
for (var x = 0; x < 10; x++) { /* more awesome stuff */ }
Now I know that JSHint is not the holy grail, but is there a way to prevent x from leaking? (assuming that's the correct terminology?
I tried:
(function () {
"use strict";
for (var x = 0; x < 10; x++) { /* do awesome stuff. 10 times! */ }
console.log(x);
for (var x /* warning here */ = 0; x < 10; x++) { /* more awesome stuff */ }
})();
So "use strict"; is not the way to go.
I tried scoping it even deeper (and this confuses me as much as that it makes me feel sick):
(function () {
"use strict";
{
for (var x = 0; x < 10; x++) { /* do awesome stuff. 10 times! */ }
}
console.log(x); // STILL WORKS...
for (var x /* warning here */ = 0; x < 10; x++) { /* more awesome stuff */ }
})();
And even worse:
On the line with the console.log invocation JSHint warns me about x being used out of scope AND the next line that I'm redeclaring x.
letbe used in a for loop instead ofvar. But, honestly, I'd ignore JSHint.vardeclarations in a function are treated as if they occurred at the start of the function. There's no scoping but function scope. @bozdozletis a JavaScript v. 6 feature and it's not universally supported.