]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/vars-on-top.md
first commit
[pve-eslint.git] / eslint / docs / rules / vars-on-top.md
1 # Require Variable Declarations to be at the top of their scope (vars-on-top)
2
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.
6
7 ## Rule Details
8
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.
11
12 Examples of **incorrect** code for this rule:
13
14 ```js
15 /*eslint vars-on-top: "error"*/
16
17 // Variable declarations in a block:
18 function doSomething() {
19 var first;
20 if (true) {
21 first = true;
22 }
23 var second;
24 }
25
26 // Variable declaration in for initializer:
27 function doSomething() {
28 for (var i=0; i<10; i++) {}
29 }
30 ```
31
32 ```js
33 /*eslint vars-on-top: "error"*/
34
35 // Variables after other statements:
36 f();
37 var a;
38 ```
39
40 Examples of **correct** code for this rule:
41
42 ```js
43 /*eslint vars-on-top: "error"*/
44
45 function doSomething() {
46 var first;
47 var second; //multiple declarations are allowed at the top
48 if (true) {
49 first = true;
50 }
51 }
52
53 function doSomething() {
54 var i;
55 for (i=0; i<10; i++) {}
56 }
57 ```
58
59 ```js
60 /*eslint vars-on-top: "error"*/
61
62 var a;
63 f();
64 ```
65
66 ```js
67 /*eslint vars-on-top: "error"*/
68
69 // Directives may precede variable declarations.
70 "use strict";
71 var a;
72 f();
73
74 // Comments can describe variables.
75 function doSomething() {
76 // this is the first var.
77 var first;
78 // this is the second var.
79 var second
80 }
81 ```
82
83 ## Further Reading
84
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/)