Skip to content
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

Initilization of a var to 'undefined' in a loop gives wrong error #1191

Closed
jontra opened this issue Jul 23, 2013 · 6 comments
Closed

Initilization of a var to 'undefined' in a loop gives wrong error #1191

jontra opened this issue Jul 23, 2013 · 6 comments

Comments

@jontra
Copy link

jontra commented Jul 23, 2013

for (var i=0; i<10; i++)
{
    var a = undefined;
    if (i%2)
        a = 1;
    if (a===undefined)
        console.log("error");
}

test.js: line 3, col 9, It's not necessary to initialize 'a' to 'undefined'.

It is necessary, since 'a' is not in the 'for' block scope.

@WolfgangKluge
Copy link
Contributor

hmm, there's nothing like a for-block scope in javascript.
To fix this issue, we have to prevent the error message if undefined is assigned to a new variable inside a loop statement. I'd like to have more discussion on that ;)

However, I think you're right - personally, I try to avoid undefined in any script. It's not a keyword and could be overwritten with any other value in non-strict code (var undefined = 1;).
So it might be a better idea to set the value to null.

As a workaround, you can use

var a;
for (var i=0; i<10; i++)
{
    a = undefined;
    if (i%2)
        a = 1;
    if (a===undefined)
        console.log("error");
}

Greetings, Wolfgang

@pvdz
Copy link

pvdz commented Dec 28, 2013

(Interesting choice to close #1142 for this issue, but whatever :) I think my main beef was that the error was non-ignorable, but I'm not sure about that at this point. )

@stevage
Copy link

stevage commented Jul 22, 2015

Whee, this is an old issue. Just came here to chime in about #1142. I ran into a bug in my code where the right answer was to change var foo; to var foo=undefined;, so it's pretty irritating to then have JSHint tell me that it's "not necessary".

@lukeapage
Copy link
Member

@stevage there you go, I made a PR to fix it.

I can also confirm that disabling W080 e.g. // jshint -W080 does work on master

@stevage
Copy link

stevage commented Jul 22, 2015

Whoa, thank you! :)

lukeapage added a commit to lukeapage/jshint that referenced this issue Aug 8, 2015
@pvdz
Copy link

pvdz commented Aug 8, 2015

👍

jugglinmike pushed a commit to jugglinmike/jshint that referenced this issue Sep 20, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants