11 In JavaScript, a variable that is declared and not initialized to any value automatically gets the value of `undefined`. For example:
16 console.log(foo === undefined); // true
19 It's therefore unnecessary to initialize a variable to `undefined`, such as:
25 It's considered a best practice to avoid initializing variables to `undefined`.
29 This rule aims to eliminate `var` and `let` variable declarations that initialize to `undefined`.
31 Examples of **incorrect** code for this rule:
36 /*eslint no-undef-init: "error"*/
44 Examples of **correct** code for this rule:
49 /*eslint no-undef-init: "error"*/
57 Please note that this rule does not check `const` declarations, destructuring patterns, function parameters, and class fields.
59 Examples of additional **correct** code for this rule:
64 /*eslint no-undef-init: "error"*/
66 const foo = undefined;
68 let { bar = undefined } = baz;
70 [quux = undefined] = quuux;
72 (foo = undefined) => {};
83 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:
85 Example of **incorrect** code for this rule:
90 for (i = 0; i < 10; i++) {
99 In this case, the `var x` is hoisted out of the loop, effectively creating:
104 for (i = 0; i < 10; i++) {
111 If you were to remove the initialization, then the behavior of the loop changes:
114 for (i = 0; i < 10; i++) {
121 This code is equivalent to:
126 for (i = 0; i < 10; i++) {
132 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.
134 If you're using such an initialization inside of a loop, then you should disable this rule.
136 Example of **correct** code for this rule, because it is disabled on a specific line:
141 /*eslint no-undef-init: "error"*/
143 for (i = 0; i < 10; i++) {
144 var x = undefined; // eslint-disable-line no-undef-init