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.
var foo = 1;
var bar;
if (foo) {
bar = 1;
} else {
bar = 2;
}
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.
var foo = 1;
var bar;
bar = 2;
This rule aims to bring consistency to variable initializations and declarations.
The rule takes two options:
"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.ignoreForLoopInit
, which indicates if initialization at declaration is allowed in for
loops when "never"
is set, since it is a very typical use case.You can configure the rule as follows:
Variables must be initialized at declaration (default)
{
"init-declarations": ["error", "always"],
}
Variables must not be initialized at declaration
{
"init-declarations": ["error", "never"]
}
Variables must not be initialized at declaration, except in for loops, where it is allowed
{
"init-declarations": ["error", "never", { "ignoreForLoopInit": true }]
}
Examples of incorrect code for the default "always"
option:
/*eslint init-declarations: ["error", "always"]*/
/*eslint-env es6*/
function foo() {
var bar;
let baz;
}
Examples of correct code for the default "always"
option:
/*eslint init-declarations: ["error", "always"]*/
/*eslint-env es6*/
function foo() {
var bar = 1;
let baz = 2;
const qux = 3;
}
Examples of incorrect code for the "never"
option:
/*eslint init-declarations: ["error", "never"]*/
/*eslint-env es6*/
function foo() {
var bar = 1;
let baz = 2;
for (var i = 0; i < 1; i++) {}
}
Examples of correct code for the "never"
option:
/*eslint init-declarations: ["error", "never"]*/
/*eslint-env es6*/
function foo() {
var bar;
let baz;
const buzz = 1;
}
The "never"
option ignores const
variable initializations.
Examples of correct code for the "never", { "ignoreForLoopInit": true }
options:
/*eslint init-declarations: ["error", "never", { "ignoreForLoopInit": true }]*/
for (var i = 0; i < 1; i++) {}
When you are indifferent as to how your variables are initialized.
This rule was introduced in ESLint 1.0.0-rc-1.
© JS Foundation and other contributors
Licensed under the MIT License.
https://eslint.org/docs/rules/init-declarations