Why does not JSLint allow “var” in a for loop?

前端 未结 3 659
离开以前
离开以前 2021-01-14 08:03

Something is wrong with my code or with plovr. I went to JSLint to get some help. However, JSLint seems to consider this as a fatal error and refuses to check more of the co

相关标签:
3条回答
  • 2021-01-14 08:43

    Because creating a bar in the for loop creates a global var. it's one of those things that JavaScript does and most people don't realize. And if you don't and you or someone else creates that same var in the scope of that function or global scope then that my friend would be one of the famous JavaScript foot guns.

    0 讨论(0)
  • 2021-01-14 08:48

    My personal opinion is that JSLint is retarded. But opinions may vary on that sensitive topic.
    — dystroy, 45 secs ago

    Hey, that's actually a valid point. JSLint is entirely constructed on opinion, and it not the word of god.

    However, general good practice is to declare all your variables in one place, at the start of the function block they are in:

    function doSomething() {
        var a, b, c, d;
        a = 1;
        c = 10;
        for( b = a; b < c; b++) {
            d = b*2 + a-c;
            alert(d);
        }
    }
    
    0 讨论(0)
  • 2021-01-14 08:57

    I agree with Niet the Dark Absol that the tool is opinion-based. Reflect on all the rules it imposes and whether they actually make sense in your specific project or not. It's also not the only "lint" tool for JavaScript. Maybe ESLint or another such tool is more suited to your needs.

    But I also disagree with him: It is not good practice to declare all your variables at the start of your function, especially not if the function is rather long, since this makes comprehension of your program much harder. IMHO this holds regardless of how the scoping of JavaScript works: It's not about program semantics, it's about code readability!

    I would argue that a variable should be declared as close to its first use as possible (i.e. in your case: in the for loop). This ensures that someone reading your code (a colleague or yourself three months from now) has too keep as little information in their head as possible. Declaring all your variables at the start forces the reader to keep all those variables in mind throughout the entire function. Questions like "what's the current value of this variable?" or "what is its purpose?" become harder to answer.

    Furthermore, you are much more tempted to reuse a variable for more than one purpose. This is not only confusing, but also dangerous! Values might "leak" from the first use to the second. This can lead to subtle, hard-to-debug problems.

    0 讨论(0)
提交回复
热议问题