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

I’d highly suggest giving Code Complete 2 by Steve McConnell a read. His argument is that you should neither declare all of your variables in one line, nor should should declare them all at the top of a routine. So, don’t do this:

function foo() {
    var a,
        b,
        c,
        d;

     /**
      * 20 lines that use a and b
      */

     /**
      * 10 lines that use c and d
      */
}

Instead, you should declare your variables close to where they are needed. In the above code, that might look like this:

function foo() {
    var a,
        b;

     /**
      * 20 lines that use a and b
      */

     var c,
         d;

     /**
      * 10 lines that use c and d
      */
}

The benefits are that you can understand at a quick glance what variables are used by a block of code by just looking at the declarations above it. You don’t need to read the code to see what variables are set, just which are declared.

Don’t write code for the compiler or for the computer. Write it for developers. Your code should be as easy to read as possible, and require as little effort as possible to understand a particular section of code.

Leave a Comment