1 # Require Variable Declarations to be at the top of their scope (vars-on-top)
3 The `vars-on-top` rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program.
4 By default variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter.
5 This rule forces the programmer to represent that behavior by manually moving the variable declaration to the top of its containing scope.
9 This rule aims to keep all variable declarations in the leading series of statements.
10 Allowing multiple declarations helps promote maintainability and is thus allowed.
12 Examples of **incorrect** code for this rule:
15 /*eslint vars-on-top: "error"*/
17 // Variable declarations in a block:
18 function doSomething() {
26 // Variable declaration in for initializer:
27 function doSomething() {
28 for (var i=0; i<10; i++) {}
33 /*eslint vars-on-top: "error"*/
35 // Variables after other statements:
40 Examples of **correct** code for this rule:
43 /*eslint vars-on-top: "error"*/
45 function doSomething() {
47 var second; //multiple declarations are allowed at the top
53 function doSomething() {
55 for (i=0; i<10; i++) {}
60 /*eslint vars-on-top: "error"*/
67 /*eslint vars-on-top: "error"*/
69 // Directives may precede variable declarations.
74 // Comments can describe variables.
75 function doSomething() {
76 // this is the first var.
78 // this is the second var.
85 * [JavaScript Scoping and Hoisting](http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html)
86 * [var Hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting)
87 * [A criticism of the Single Var Pattern in JavaScript, and a simple alternative](http://danielhough.co.uk/blog/single-var-pattern-rant/)
88 * [Multiple var statements in JavaScript, not superfluous](http://benalman.com/news/2012/05/multiple-var-statements-javascript/)