]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/no-undef-init.md
first commit
[pve-eslint.git] / eslint / docs / rules / no-undef-init.md
1 # Disallow Initializing to undefined (no-undef-init)
2
3 In JavaScript, a variable that is declared and not initialized to any value automatically gets the value of `undefined`. For example:
4
5 ```js
6 var foo;
7
8 console.log(foo === undefined); // true
9 ```
10
11 It's therefore unnecessary to initialize a variable to `undefined`, such as:
12
13 ```js
14 var foo = undefined;
15 ```
16
17 It's considered a best practice to avoid initializing variables to `undefined`.
18
19
20 ## Rule Details
21
22 This rule aims to eliminate variable declarations that initialize to `undefined`.
23
24 Examples of **incorrect** code for this rule:
25
26 ```js
27 /*eslint no-undef-init: "error"*/
28 /*eslint-env es6*/
29
30 var foo = undefined;
31 let bar = undefined;
32 ```
33
34 Examples of **correct** code for this rule:
35
36 ```js
37 /*eslint no-undef-init: "error"*/
38 /*eslint-env es6*/
39
40 var foo;
41 let bar;
42 const baz = undefined;
43 ```
44
45 ## When Not To Use It
46
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:
48
49 Example of **incorrect** code for this rule:
50
51 ```js
52 for (i = 0; i < 10; i++) {
53 var x = undefined;
54 console.log(x);
55 x = i;
56 }
57 ```
58
59 In this case, the `var x` is hoisted out of the loop, effectively creating:
60
61 ```js
62 var x;
63
64 for (i = 0; i < 10; i++) {
65 x = undefined;
66 console.log(x);
67 x = i;
68 }
69 ```
70
71 If you were to remove the initialization, then the behavior of the loop changes:
72
73 ```js
74 for (i = 0; i < 10; i++) {
75 var x;
76 console.log(x);
77 x = i;
78 }
79 ```
80
81 This code is equivalent to:
82
83 ```js
84 var x;
85
86 for (i = 0; i < 10; i++) {
87 console.log(x);
88 x = i;
89 }
90 ```
91
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.
93
94 If you're using such an initialization inside of a loop, then you should disable this rule.
95
96 Example of **correct** code for this rule, because it is disabled on a specific line:
97
98 ```js
99 /*eslint no-undef-init: "error"*/
100
101 for (i = 0; i < 10; i++) {
102 var x = undefined; // eslint-disable-line no-undef-init
103 console.log(x);
104 x = i;
105 }
106 ```
107
108 ## Related Rules
109
110 * [no-undefined](no-undefined.md)
111 * [no-void](no-void.md)