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.
function doSomething(things) {
// Loop that does something
for (var i= 0; i<things.length; i++) {
var thing= things[i];
thing.doPartOfSomething();
}
// Loop that does something else
for (var i= 0; i<things.length; i++) {
var thing= things[i];
doAnotherPartOfSomething(thing);
}
}
Here's two independent usages of the same variables `i` and `thing` in
the same function. A purist might argue that you shouldn't reuse a
variable in the same function, but in reality the alternatives are
usually worse:
- choosing different names each time means names have to be longer
and/or less natural;
- putting each independent or semi-independent block in its own function
leads to an explosion of tiny unmanageable functions.
So with the recommendation to move the `var` to the top:
function doSomething(things) {
var i, thing;
// Loop that does something
for (i= 0; i<things.length; i++) {
thing= things[i];
thing.doPartOfSomething();
}
// Loop that does something else
for (i= 0; i<things.length; i++) {
thing= things[i];
doAnotherPartOfSomething(thing);
}
}
But now there's a gap between declaration and usage, one that gets more
impractical the longer the function gets. And there's unnecessary
coupling between those previously-independent blocks. If during a
refactoring, you cut-and-paste one of the loops out of `doSomething`
into another function, you've got yourself an accidental global with all
the problems that incurs.
So, I'd say: don't move all `var` declarations to the top after all.
Instead, declare `var` every time you first assign a variable, not
don't care if it existed previously.
--
And Clover
mailto:[email protected] http://www.doxdesk.com
skype:uknrbobince gtalk:[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]