Disallow initializing variables to undefined
Some problems reported by this rule are automatically fixable by the --fix
command line option
In JavaScript, a variable that is declared and not initialized to any value automatically gets the value of undefined
. For example:
It’s therefore unnecessary to initialize a variable to undefined
, such as:
It’s considered a best practice to avoid initializing variables to undefined
.
This rule aims to eliminate var
and let
variable declarations that initialize to undefined
.
Examples of incorrect code for this rule:
Examples of correct code for this rule:
Please note that this rule does not check const
declarations, destructuring patterns, function parameters, and class fields.
Examples of additional correct code for this rule:
There is one situation where initializing to undefined
behaves differently than omitting the initialization, and that’s when a var
declaration occurs inside of a loop. For example:
Example of incorrect code for this rule:
In this case, the var x
is hoisted out of the loop, effectively creating:
If you were to remove the initialization, then the behavior of the loop changes:
This code is equivalent to:
This produces a different outcome than defining var x = undefined
in the loop, as x
is no longer reset to undefined
each time through the loop.
If you’re using such an initialization inside of a loop, then you should disable this rule.
Example of correct code for this rule, because it is disabled on a specific line:
This rule was introduced in ESLint v0.0.6.
© OpenJS Foundation and other contributors
Licensed under the MIT License.
https://eslint.org/docs/latest/rules/no-undef-init