12 In JavaScript, a variable that is declared and not initialized to any value automatically gets the value of `undefined`. For example:
17 console.log(foo === undefined); // true
20 It's therefore unnecessary to initialize a variable to `undefined`, such as:
26 It's considered a best practice to avoid initializing variables to `undefined`.
30 This rule aims to eliminate `var` and `let` variable declarations that initialize to `undefined`.
32 Examples of **incorrect** code for this rule:
37 /*eslint no-undef-init: "error"*/
45 Examples of **correct** code for this rule:
50 /*eslint no-undef-init: "error"*/
58 Please note that this rule does not check `const` declarations, destructuring patterns, function parameters, and class fields.
60 Examples of additional **correct** code for this rule:
65 /*eslint no-undef-init: "error"*/
67 const foo = undefined;
69 let { bar = undefined } = baz;
71 [quux = undefined] = quuux;
73 (foo = undefined) => {};
84 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:
86 Example of **incorrect** code for this rule:
91 for (i = 0; i < 10; i++) {
100 In this case, the `var x` is hoisted out of the loop, effectively creating:
105 for (i = 0; i < 10; i++) {
112 If you were to remove the initialization, then the behavior of the loop changes:
115 for (i = 0; i < 10; i++) {
122 This code is equivalent to:
127 for (i = 0; i < 10; i++) {
133 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.
135 If you're using such an initialization inside of a loop, then you should disable this rule.
137 Example of **correct** code for this rule, because it is disabled on a specific line:
142 /*eslint no-undef-init: "error"*/
144 for (i = 0; i < 10; i++) {
145 var x = undefined; // eslint-disable-line no-undef-init