Skip to content Skip to sidebar Skip to footer

Javascript Variable Declarations At The Head Of A Function

I've been told that javascript variables should all come before they are used in a function, such that: function contrived() { var myA, myB; myA = 10; myB = 20; return my

Solution 1:

I guess some people might prefer the former style because that's how it works inside. All local variables exist for the entire lifetime of the function, even if you use var to declare them in the middle of the function.

There's nothing wrong with declaring variables later in the function, syntax-wise, it might just be confusing as the variables will then exist before the line that declares them. Hence this function:

function bar() {
    alert(foo); // Alerts "undefined". Not an error because the variable does exist.var foo = 10;
    alert(foo); // Alerts the value 10.
}

Is equivalent to this:

function bar() {
    var foo;
    alert(foo);
    foo = 10;
    alert(foo);
}

Another related fact is that nested function definitions (done using function foo() { ... }) will get moved to the top of the containing function as well, so they will be available even if the code that calls them comes before them.

Solution 2:

Yes, the variable declaration should come at the top of the function:

function foo() {
  var a, b;
}

However, initializing variables can be part of the declaration:

function foo() {
  var a = 10, b = 20;
}

The reasoning behind declaring all variables at the top of the function where they are used is to avoid scope confusion.

Here is an example of bad code:

functionfoo() {
  var b;
  for (var i = 0; i < 5; i++) {
    var a;
    a = b = i;
    setTimeout(function(){
      console.log(a, b);
    }, 1000);
  }
}

If you execute the code, it will log 4, 4 5 times, rather than counting up. This is because only functions act as closures and introduce new scope. In JavaScript, any var declaration within a function gets executed at the beginning of the function.

This makes the above error much more visible:

functionfoo() {
  var a, b, i;
  for (i = 0; i < 5; i++) {
    a = b = i;
    setTimeout(function(){
      console.log(a, b);
    }, 1000);
  }
}

Solution 3:

There is no difference in this case between this two. I'd go with:

function furtherContrivance() {
  var myA = 10,
      myB = 20;

  return myA + myB;
}

which is knows as single var pattern in javascript.

What you really need to take care of is defining your variables in the beginning of your functions. There is a thing in javascript called variables hoisting which means that variable definitions used in function "raise" on top. It's best described by an example:

var x = 'global'; // global (bounded to a global object which is window in browsers)
function func() { 
    alert(x); // undefined (you expected 'global', right?)var x = 'local';
    alert(x); // local
}
func();

what really happens is called (as I said) variables hoisting (definition of x raises on top), so the code above is actually the same as:

var x = 'global';
function func() {
    var x; // definition of `x` raised on top (variables hoisting)
    alert(x); // undefined in a local scope
    x = 'local';
    alert(x);
}

What a javscript interpreter does is it looks inside a function, gathers locally defined variables and raises them on top - this might be a good reason why you should use single var pattern.

Solution 4:

In the example you give this is absolutely not the case. In a language like Javascript, it will be more of a developer preference, but it won't have any impact on the result.

Solution 5:

Yes, place them at the top. It adds to code clarity.

Try this example:

var x = 1;

(function() {

    x++;
    alert( x );  // What will this alert show?var x = 'done';
    alert( x );

})();

Looks like it should alert 2, but it alerts NaN.

This is because the variable declaration is hoisted to the top, but the initialization stays in the same place.

So what is actually happening is:

var x = 1;

(function() {
    var x;

    x++;
    alert( x );  // What will this alert show? NaN

    x = 'done';
    alert( x );

})();

...which makes the NaN expected.

Post a Comment for "Javascript Variable Declarations At The Head Of A Function"