Require or disallow initialization in variable declarations
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.
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.
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)
Variables must not be initialized at declaration
Variables must not be initialized at declaration, except in for loops, where it is allowed
Examples of incorrect code for the default "always"
option:
Examples of correct code for the default "always"
option:
Examples of incorrect code for the "never"
option:
Examples of correct code for the "never"
option:
The "never"
option ignores const
variable initializations.
Examples of correct code for the "never", { "ignoreForLoopInit": true }
options:
When you are indifferent as to how your variables are initialized.
This rule was introduced in ESLint v1.0.0-rc-1.
© OpenJS Foundation and other contributors
Licensed under the MIT License.
https://eslint.org/docs/latest/rules/init-declarations