1 # Disallow Initializing to undefined (no-undef-init)
3 In JavaScript, a variable that is declared and not initialized to any value automatically gets the value of `undefined`. For example:
8 console.log(foo === undefined); // true
11 It's therefore unnecessary to initialize a variable to `undefined`, such as:
17 It's considered a best practice to avoid initializing variables to `undefined`.
22 This rule aims to eliminate `var` and `let` variable declarations that initialize to `undefined`.
24 Examples of **incorrect** code for this rule:
27 /*eslint no-undef-init: "error"*/
33 Examples of **correct** code for this rule:
36 /*eslint no-undef-init: "error"*/
42 Please note that this rule does not check `const` declarations, destructuring patterns, function parameters, and class fields.
44 Examples of additional **correct** code for this rule:
47 /*eslint no-undef-init: "error"*/
49 const foo = undefined;
51 let { bar = undefined } = baz;
53 [quux = undefined] = quuux;
55 (foo = undefined) => {};
64 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:
66 Example of **incorrect** code for this rule:
69 for (i = 0; i < 10; i++) {
76 In this case, the `var x` is hoisted out of the loop, effectively creating:
81 for (i = 0; i < 10; i++) {
88 If you were to remove the initialization, then the behavior of the loop changes:
91 for (i = 0; i < 10; i++) {
98 This code is equivalent to:
103 for (i = 0; i < 10; i++) {
109 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.
111 If you're using such an initialization inside of a loop, then you should disable this rule.
113 Example of **correct** code for this rule, because it is disabled on a specific line:
116 /*eslint no-undef-init: "error"*/
118 for (i = 0; i < 10; i++) {
119 var x = undefined; // eslint-disable-line no-undef-init
127 * [no-undefined](no-undefined.md)
128 * [no-void](no-void.md)