2

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.

Anemoia
  • 7,928
  • 7
  • 46
  • 71
  • javascript is not block scoped, it's function scoped. Any variable declared in a function can be seen anywhere in that function. – Matt R May 15 '14 at 16:38
  • I've seen `let` be used in a for loop instead of `var`. But, honestly, I'd ignore JSHint. – bozdoz May 15 '14 at 16:39
  • All `var` declarations in a function are treated as if they occurred at the start of the function. There's no scoping but function scope. @bozdoz `let` is a JavaScript v. 6 feature and it's not universally supported. – Pointy May 15 '14 at 16:39
  • See [Variable hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting) – Ruan Mendes May 15 '14 at 16:41

1 Answers1

0

Variables are only scoped to functions in JavaScript, not blocks. If you absolutely needed to scope each for loop separately, you would need to do something like this:

(function () {
    for (var x = 0; x < 10; x++) { /* do awesome stuff. 10 times! */ }
})();
(function () {
    for (var x = 0; x < 10; x++) { /* more awesome stuff */ }
})();

Or, you could just reuse the x variable without redeclaring it, which would still work fine.

Alexis King
  • 43,109
  • 15
  • 131
  • 205
  • 1
    In general it's considered good practice to declare all your variables up front, in this case just `var x;` at the start of the function. That way, you don't have to track down inline `var`s. – Niet the Dark Absol May 15 '14 at 16:40
  • @NiettheDarkAbsol, I find that useful for working out if my function needs to be refactored - too many variables might mean that some functionality can be moved to its own function. – Andy May 15 '14 at 16:43