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
the alert window will contain undefined. because internally, it’s been changed into this:
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.