I\'ve heard that it is a good technique to define your variables at the top of a function, so you don\'t end up with variable hoisting problems. This:
// Beginni
I don't think so.
Here is how I would write that (ignoring names):
function something(){
var a,
b,
c = 1,
d,
e;
// Do something
}
This only looks silly in the above because 1) the names suck 2) the variables are not assigned in the "declaration" -- most code can be written with immutable (assigned-once) variables and I find this to simplify code. I use this for multiple reasons including clarity and resistance to formatting changes (that is, I can change the initial values, add/or remove declarations, etc, without mucking about the formatting of the other lines).
I don't think so.
For instance, here is how I write loops:
for (var i = 0; i < x; i++) {
var elm = elms[i];
...
}
And some people will go "BUT THE VAR IS HOISTED TO THE TOP OF THE FUNCTION!" or "A VARIABLE IS FUNCTION-SCOPED!". Well, indeed. However, that allows me to easily visually see that this is an error, even if the JavaScript engine won't help:
for (var i = 0; i < x; i++) {
var elm = elms[i];
...
}
...
// valid JS but since I consider this construct *invalid*
// I know this is a *bug* in my code
alert(elm);
As far as when I assign to variables caught in closures: it depends. If the variable is used in only a single closure I generally put it right above. This lets me know it should only be used in that closure. If the variable is shared (e.g. self
) I put it above all the applicable closures -- generally in the "variable declaration section" of the function. This lets me know it has a "function-wide scope" (read: likely to be used in multiple bindings).
To address the "for-each closure issue" -- just learn the language. Keeping variable "declarations" close to the closure does not affect this in anyway. If the construct is not understood, it really doesn't matter how the code is written.
I use these approaches to/because:
Happy coding.