Is the definition of each variable at the top always the best approach?

advertisements

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:

// Beginning of file

function something(){
    var a, b, c = 1, d, e;
    // Do something
}

// End of file

is a good example (excluding the bad variable names, of course).

My question is: Is this always the best approach? What if you are working with a lot of variables? Should they really all just be plopped on one line?


"Should they really all just be plopped on one line?"

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).

"Is defining every variable at the top always the best approach?"

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:

  1. Have consistent easy-to-scan code.
  2. Write code that tells me when it's wrong.
  3. I prefer code that is amendable to altering without changing structure.
  4. Self-documenting code means less comments.
  5. I like to "read vertically"

Happy coding.