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

我是研究僧i 提交于 2020-02-14 19:54:19

问题


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 code:

for (var i = 0; i < data.length; i += 4) {

Why? I like this way of declaring "I".

JSHint does not seem to be an alternative if you are on Windows. I am trying The Online Lint at the moment. I have a feeling that this bug will be a bit difficult to find so I would be glad for suggestions about good code checkers.


回答1:


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.




回答2:


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);
    }
}



回答3:


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.



来源:https://stackoverflow.com/questions/23105006/why-does-not-jslint-allow-var-in-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!