]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/no-unreachable.md
bump version to 8.4.0-3
[pve-eslint.git] / eslint / docs / rules / no-unreachable.md
1 # disallow unreachable code after `return`, `throw`, `continue`, and `break` statements (no-unreachable)
2
3 Because the `return`, `throw`, `break`, and `continue` statements unconditionally exit a block of code, any statements after them cannot be executed. Unreachable statements are usually a mistake.
4
5 ```js
6 function fn() {
7 x = 1;
8 return x;
9 x = 3; // this will never execute
10 }
11 ```
12
13 Another kind of mistake is defining instance fields in a subclass whose constructor doesn't call `super()`. Instance fields of a subclass are only added to the instance after `super()`. If there are no `super()` calls, their definitions are never applied and therefore are unreachable code.
14
15 ```js
16 class C extends B {
17 #x; // this will never be added to instances
18
19 constructor() {
20 return {};
21 }
22 }
23 ```
24
25 ## Rule Details
26
27 This rule disallows unreachable code after `return`, `throw`, `continue`, and `break` statements. This rule also flags definitions of instance fields in subclasses whose constructors don't have `super()` calls.
28
29 Examples of **incorrect** code for this rule:
30
31 ```js
32 /*eslint no-unreachable: "error"*/
33
34 function foo() {
35 return true;
36 console.log("done");
37 }
38
39 function bar() {
40 throw new Error("Oops!");
41 console.log("done");
42 }
43
44 while(value) {
45 break;
46 console.log("done");
47 }
48
49 throw new Error("Oops!");
50 console.log("done");
51
52 function baz() {
53 if (Math.random() < 0.5) {
54 return;
55 } else {
56 throw new Error();
57 }
58 console.log("done");
59 }
60
61 for (;;) {}
62 console.log("done");
63 ```
64
65 Examples of **correct** code for this rule, because of JavaScript function and variable hoisting:
66
67 ```js
68 /*eslint no-unreachable: "error"*/
69
70 function foo() {
71 return bar();
72 function bar() {
73 return 1;
74 }
75 }
76
77 function bar() {
78 return x;
79 var x;
80 }
81
82 switch (foo) {
83 case 1:
84 break;
85 var x;
86 }
87 ```
88
89 Examples of additional **incorrect** code for this rule:
90
91 ```js
92 /*eslint no-unreachable: "error"*/
93
94 class C extends B {
95 #x; // unreachable
96 #y = 1; // unreachable
97 a; // unreachable
98 b = 1; // unreachable
99
100 constructor() {
101 return {};
102 }
103 }
104 ```
105
106 Examples of additional **correct** code for this rule:
107
108 ```js
109 /*eslint no-unreachable: "error"*/
110
111 class D extends B {
112 #x;
113 #y = 1;
114 a;
115 b = 1;
116
117 constructor() {
118 super();
119 }
120 }
121
122 class E extends B {
123 #x;
124 #y = 1;
125 a;
126 b = 1;
127
128 // implicit constructor always calls `super()`
129 }
130
131 class F extends B {
132 static #x;
133 static #y = 1;
134 static a;
135 static b = 1;
136
137 constructor() {
138 return {};
139 }
140 }
141 ```