Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Should I declare all variables at the top?

It's best to declare variables when you first use them to ensure that they are always initialized to some valid value and that their intended use is always apparent. The alternative is typically to declare all variables in one location, typically at the top of the block or, even worse, at the top of a function.

Where should you define variables?

Ideally, declare and define each variable close to where it's first used. A declaration establishes a variable's type. A definition assigns the variable a specific value. In languages that support it, such as C++ and Java, variables should be declared and defined close to where they are first used.

What are the benefits of keeping declarations at the top?

Declare variables at the top of the function as a means of documenting all variables used in one place. It also avoids confusion resulting from someone imagining that a variable is block-scoped when it is in fact not, as in the following: var i=0; if (true) { var i=1; } // what is i?

Why is it important to declare a variable?

A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable.


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.


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


In languages with block scope, it is usually recommended that variables be declared at the site of first use.

But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. This way you don't fool yourself or other people about the variable's scope.

EDIT: Many people work with several languages simultaneously. Often JavaScript is the only one among them without the block scope.


This is a style question. Not a functionality question.

The javascript parser will take this code

function() {
   dostuff();
   var i = 4;
}

and turn it into :

function() {
   var i;
   dostuff();
   i = 4;
}

As for the style question. No thank you I thought we left that behind with ANSI C.

What you want to do is declare functions at the top of their "scope"

If the "scope" of a variable is the entire function then declare them at the top. If the "scope" is a subset of a function then declare them at the start of the subset.

treat "scope" as logical scope rather then function scope.

This should ensure maximum readability.


This is really just a matter of preference. For example, if my method only contains a for loop, then I won't extract the loop variables to the top:

var func = function(arr) {
    for (var i = 0, len = arr.length; i < len; i++) {
        // array processing here
    }
}

Almost all other times though I will place ALL variables at the top for hoisting reasons. If you find that there are too many variables at the top of your function, it could be an indication that your method is doing too much work, and should consider extracting a portion of it into some sort of helper method. This will let you organize your variables based on functionality.