One var per function in JavaScript? One var per function in JavaScript? javascript javascript

One var per function in JavaScript?


The problem is that, whether you realise it or not, javascript invisibly moves all the var declarations to the top of the function scope.

so if you have a function like this

var i = 5;function testvar () {     alert(i);     var i=3;}testvar();

the alert window will contain undefined. because internally, it's been changed into this:

var i = 5;function testvar () {     var i;     alert(i);     i=3;}testvar();

this is called "hoisting".The reason crockford so strongly advocates var declarations go at the top, is that it makes the code visibly match what it's going to do, instead of allowing invisible and unexpected behavior to occur.


Basically in JavaScript blocks ({ ... }) do not introduce a new scope, there is only function-scope, so no scope is created on any other statement.

A variable introduced anywhere in a function is visible everywhere in the function.

For example:

function myFunction(){  var one = 1;  if (one){    var two = one + 1;  }  (function () {    var three = one + two;  })();  // at this point both variables *one* and *two* are accessible but   // the variable *three* was declared in the scope of a inner function  // and is not accessible  at this point.}

In languages with block scope, it recommended to declare the variables at the point of first use, but since JavaScript does not have block scope, it is better to declare all of a function's variables at the top of the function.

Check this article.


The lack of block scope explains the code below:

var a = 1;if (something) {    var a = 2;}alert(a); // Alerts "2"

In most C-style (as in syntax) languages, the var a = 2 definition would define 'a' only for the scope of the if block. Using a single var statement at the top of the function helps to avoid this quirk of Javascript, which is not always as obvious as the above, and would be unexpected to C/C#/Java programmers.