Disallow unreachable code after return
, throw
, continue
, and break
statements
The "extends": "eslint:recommended"
property in a configuration file enables this rule
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.
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.
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.
Examples of incorrect code for this rule:
/*eslint no-unreachable: "error"*/
function foo() {
return true;
console.log("done");
}
function bar() {
throw new Error("Oops!");
console.log("done");
}
while(value) {
break;
console.log("done");
}
throw new Error("Oops!");
console.log("done");
function baz() {
if (Math.random() < 0.5) {
return;
} else {
throw new Error();
}
console.log("done");
}
for (;;) {}
console.log("done");
Examples of correct code for this rule, because of JavaScript function and variable hoisting:
Examples of additional incorrect code for this rule:
Examples of additional correct code for this rule:
This rule was introduced in ESLint v0.0.6.
© OpenJS Foundation and other contributors
Licensed under the MIT License.
https://eslint.org/docs/latest/rules/no-unreachable