On Mon, Jan 17, 2011 at 11:10 PM, Ryan Grove <[email protected]> wrote: > On Mon, Jan 17, 2011 at 1:50 PM, And Clover <[email protected]> wrote: >> On Sat, 2011-01-15 at 17:38 -0800, Ryan Grove wrote: >>> If another developer comes along and adds some code after the second >>> var statement but before the second loop that assumes that i and/or >>> thing are undefined >> >> The chances that someone *wants* to use an undefined variable, and >> consequently receive a ReferenceError, seem negligible. >> >> Locality-of-declaration-to-use is a win for practical maintainability. > > That's just the thing, though. There is no such thing as "locality of > declaration to use" in JavaScript. Regardless of where you put your > var statement, the declaration will be hoisted to the top of the > scope. The result is that any var statement that isn't at the top of > the scope will be misleading. > > I agree with you that it would be nice to be able to keep variable > declarations as close as possible to where those variables are used, > but JavaScript doesn't work that way. > >> Var-at-the-top-of-the-function is a win for some kind of theoretical >> purity, that will bite you (not just your inexperienced team-mates) when >> you start moving code about. > > Code clarity isn't just about theoretical purity, it's about reducing > the likelihood of mistakes being made. By keeping var declarations at > the top of the function, you ensure that what the code *actually* does > and what it *appears* to do are the same thing, rather than relying on > the developer to understand that what he or she sees is not what's > really happening. > > You're right that it causes a bit more work when refactoring, but I > think that's a reasonable tradeoff. Small changes should be easier and > less mistake-prone than large changes, and that's exactly what this > best practice is intended to do. >
Have to copy this well written explanation and just paste it in future debates over this :-) -- Diego > - Ryan > > -- > 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] > -- 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]
