3 ms·
>due to the 'for(var i=0...' failing even with -vars enabled That's because `for(var i=0...` is completely bogus. What if you have two of those loops? Are you
by ahoge 14y ago
>due to the 'for(var i=0...' failing even with -vars enabled
That's because `for(var i=0...` is completely bogus. What if you have two of those loops? Are you going to put `var` in the first one, but not in the second one? Are you going to use 'i' in the first one and 'k' in the second one?
What if you need some refactoring and those two loops switch places?
It's fine if you like Java, but JavaScript is different. When in Rome, do as the Romans do. I also wish there would be block scope, but merely pretending there is doesn't make it so.
It's better if you declare all of your variables at the very top of the innermost function, because that's where they effectively are (thanks to hoisting). It's better if your code reflects how it's actually working, because that will always make it easier to comprehend.
Once there is `let`, you should switch to Java's "declare on first use" rule and never use `var` again.
- nfriedly 14y agoRight, I understand why. And, if I have two in the same scope, jshint will rightly alert me that I have an error. But I don't have this issue once in ~20k lines of js. So in my case, jslint not honoring its own -vars option was just a nuisance. And while I agree that declaring vars at the top is closer to whats actually happening, I disagree that it makes it easier to comprehend.
- ahoge 14y agofunction foo () { x = 5; // totally fine ... var x; // because we declare it here }
- Joeri 14y agoWhat is the bug that can result from the "for(var i=0)" pattern? None, beause browsers ignore the second var for the same variable and do te ituitively right thing. What's the bug that results from the "var i; for(i=0)" pattern? Someone refactors the "var i" away and you end up with a global var. So, really, while the pedantic answer is to forbid the pattern, the pragmatic answer is to recommend it.
- ahoge 14y ago>What's the bug that results from the "var i; for(i=0)" pattern? Someone refactors the "var i" away and you end up with a global var. Wrong. JSLint will complain and then you'll fix it. That's why you use JSLint. It can find stupid things like this easily and accurately.