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 variable declarations that initialize to `undefined`.
24 Examples of **incorrect** code for this rule:
27 /*eslint no-undef-init: "error"*/
34 Examples of **correct** code for this rule:
37 /*eslint no-undef-init: "error"*/
42 const baz = undefined;
47 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:
49 Example of **incorrect** code for this rule:
52 for (i = 0; i < 10; i++) {
59 In this case, the `var x` is hoisted out of the loop, effectively creating:
64 for (i = 0; i < 10; i++) {
71 If you were to remove the initialization, then the behavior of the loop changes:
74 for (i = 0; i < 10; i++) {
81 This code is equivalent to:
86 for (i = 0; i < 10; i++) {
92 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.
94 If you're using such an initialization inside of a loop, then you should disable this rule.
96 Example of **correct** code for this rule, because it is disabled on a specific line:
99 /*eslint no-undef-init: "error"*/
101 for (i = 0; i < 10; i++) {
102 var x = undefined; // eslint-disable-line no-undef-init
110 * [no-undefined](no-undefined.md)
111 * [no-void](no-void.md)