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.

4
  • javascript is not block scoped, it's function scoped. Any variable declared in a function can be seen anywhere in that function. Commented May 15, 2014 at 16:38
  • I've seen let be used in a for loop instead of var. But, honestly, I'd ignore JSHint. Commented May 15, 2014 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. Commented May 15, 2014 at 16:39
  • See Variable hoisting Commented May 15, 2014 at 16:41

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 vars.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.