jshint/jshint — pull request #1283 by Druotic (2013-09-28 00:27:38+00:00)
Title: Added option to enforce variable declaration at the top of declaring scope

This patch adds the option to enforce top level variable declaration. When this option `vartop` is true, variables must be declared where a javascript interpreter would "hoist" them. This usually means the top of the function or global scope. More generally, any variable declaration should be made where it would be 'hoisted' by a javascript interpreter (For functions - at the top of the function body. For the outermost/global scope, at the top of the file).

For more info, see function hoisting at http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

For example:
function foo () {
var a;
var b;
var c;
if ( blah ) {
...
}
}
The above example is okay. The following example is NOT okay.
function bar () {
var a;
if (blah) {
...
}
var b; //this should cause jshint to warn
}

Note that iterator variable declarations are also hoisted in for loop statements!! Example:
//Okay!
function f () {
var a;
var i;
for ( i = 0; i < 10; i++) {
...
}
}
//NOT okay!
function bad_f () {
var a;
for (var i = 0; i < 10; i++) {
...
}
}

This helps clarify where the scope of the variable truly extends. Also note that a variable declared inside the for loop would also be visible not only inside the loop, but also through the entire function! Because javascript has function level scoping and NOT block level, a lot of confusion can arise from less experienced javascript developers. Using this flag will help prevent potential bugs arising from scoping issues. Though it may look a little odd at first, it can be very beneficial in the long run.

Note that this is an initial implementation. Most obvious cases are tested and all tested cases work properly. There could possibly still be some cases which I have not covered, but this is a good starting point.

Fixes: issue (feature request) #1263