1 # require or disallow initialization in variable declarations (init-declarations)
3 In JavaScript, variables can be assigned during declaration, or at any point afterwards using an assignment statement. For example, in the following code, `foo` is initialized during declaration, while `bar` is initialized later.
18 This rule is aimed at enforcing or eliminating variable initializations during declaration. For example, in the following code, `foo` is initialized during declaration, while `bar` is not.
27 This rule aims to bring consistency to variable initializations and declarations.
31 The rule takes two options:
33 1. A string which must be either `"always"` (the default), to enforce initialization at declaration, or `"never"` to disallow initialization during declaration. This rule applies to `var`, `let`, and `const` variables, however `"never"` is ignored for `const` variables, as unassigned `const`s generate a parse error.
34 2. An object that further controls the behavior of this rule. Currently, the only available parameter is `ignoreForLoopInit`, which indicates if initialization at declaration is allowed in `for` loops when `"never"` is set, since it is a very typical use case.
36 You can configure the rule as follows:
38 Variables must be initialized at declaration (default)
42 "init-declarations": ["error", "always"],
46 Variables must not be initialized at declaration
50 "init-declarations": ["error", "never"]
54 Variables must not be initialized at declaration, except in for loops, where it is allowed
58 "init-declarations": ["error", "never", { "ignoreForLoopInit": true }]
64 Examples of **incorrect** code for the default `"always"` option:
67 /*eslint init-declarations: ["error", "always"]*/
76 Examples of **correct** code for the default `"always"` option:
79 /*eslint init-declarations: ["error", "always"]*/
91 Examples of **incorrect** code for the `"never"` option:
94 /*eslint init-declarations: ["error", "never"]*/
101 for (var i = 0; i < 1; i++) {}
105 Examples of **correct** code for the `"never"` option:
108 /*eslint init-declarations: ["error", "never"]*/
118 The `"never"` option ignores `const` variable initializations.
120 ### ignoreForLoopInit
122 Examples of **correct** code for the `"never", { "ignoreForLoopInit": true }` options:
125 /*eslint init-declarations: ["error", "never", { "ignoreForLoopInit": true }]*/
126 for (var i = 0; i < 1; i++) {}
129 ## When Not To Use It
131 When you are indifferent as to how your variables are initialized.