One var per function in JavaScript?

I've been using JSLint to make me feel bad about my JavaScript. It is great, by the way. There is one check that I don't quite understand and I'd like your views, please.

From jslint.com:

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. It is recommended that a single var statement be used per function.

What is the last sentance in bold really saying? I think I should be declaring multiple variables like this?

var foo = 1, bar = 2;

And, is the "wise" part just a programming style to discourage errors down the line or is there more to it than that?

Thanks for your help.


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.

链接地址: http://www.djcxy.com/p/2774.html

上一篇: 如何删除使用.css()函数添加的样式?

下一篇: JavaScript中的每个函数都有一个变量?