disallow unreachable code after return, throw, continue, and break statements (no-unreachable)

禁止在 returnthrowcontinuebreak 语句后出现不可达代码 (no-unreachable)

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.

因为 returnthrowcontinuebreak 语句无条件地退出代码块,其之后的任何语句都不会被执行。不可达语句通常是个错误。

function fn() {
    x = 1;
    return x;
    x = 3; // this will never execute
}

Rule Details

This rule disallows unreachable code after return, throw, continue, and break statements.

该规则禁止在 returnthrowcontinuebreak 语句后出现不可达代码。

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:

正确 代码示例,因为 JavaScript 函数和变量提升:

/*eslint no-unreachable: "error"*/

function foo() {
    return bar();
    function bar() {
        return 1;
    }
}

function bar() {
    return x;
    var x;
}

switch (foo) {
    case 1:
        break;
        var x;
}

Version

This rule was introduced in ESLint 0.0.6.

该规则在 ESLint 0.0.6 中被引入。

Resources