Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript variable declarations at the head of a function

Tags:

javascript

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 myA + myB;
}

Is prefered over:

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

  return myA + myB;
}

Is this the case? And why is that?

like image 868
Khanzor Avatar asked Jan 27 '26 01:01

Khanzor


2 Answers

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.

like image 168
Matti Virkkunen Avatar answered Jan 28 '26 15:01

Matti Virkkunen


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.

like image 27
Nemoden Avatar answered Jan 28 '26 15:01

Nemoden