On Sat, Jan 15, 2011 at 12:25 PM, And Clover <[email protected]> wrote:
> On Fri, 2011-01-14 at 10:12 -0800, cancel bubble wrote: > > I understand that it's good practice to declare all your vars at the > top of > your function > > I disagree. This is one part of Crockford Dogma I think is badly > mistaken. It's a habit from other languages that is, IMO, actively > unhelpful in JS. That's not entirely true. The theory or "best practice" in js is not so much about/against redeclaration of the same variable. Redeclaring the same var twice is ignored by js, not affecting the existing var. The "best practice" is about hoisting. It should make obvious that there's no such thing as block scope in js. If all variables are declared at the top, there's no risk at all of anyone thinking variables in the loop are bound to "a block scope of that loop". If you declare the var inline, in the for-header, somebody might think that the variable is local to the loop only. (Ok, it maybe won't make obvious that there's no block scope, but no programmer will be confused by thinking that the variable is in fact block scope bound) Now, it's fine to do so for your own projects. Nobody's gonna argue with that. Ok, virtually nobody ;) But when it comes to group projects it can become a different matter altogether. Especially if you don't really control who's going to be part of that group. Eg, at work, you don't usually get to pick who you're working with, or who gets to work on your project. Even if you do, there's a chance you don't know what the future might bring. Somebody else might have to continue that project after you leave the company. And the thing about that is; you don't know whether those people actually know about hoisting. So for group/work projects, the "best practice" suddenly makes sense. But for your own projects or whatever, sure, do whatever you feel comfortable with :) Oh and also, declaring the same var twice can indicate a flaw in your logic. I agree though that Douglas should make it an optional warning, not a (blocking) error. - peter -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/[email protected]/ To search via a non-Google archive, visit here: http://www.mail-archive.com/[email protected]/ To unsubscribe from this group, send email to [email protected]
