# no-unreachable
在 return、throw、continue 和 break 语句之后禁止无法访问的代码
配置文件中的 "extends": "eslint:recommended" 属性启用了该规则
因为 return、throw、break 和 continue 语句无条件退出代码块,所以后面的任何语句都无法执行。无法访问的语句通常是一个错误。
function fn() {
    x = 1;
    return x;
    x = 3; // this will never execute
}
另一种错误是在其构造函数没有调用 super() 的子类中定义实例字段。子类的实例字段只添加到 super() 之后的实例中。如果没有 super() 调用,则它们的定义永远不会应用,因此是无法访问的代码。
class C extends B {
    #x; // this will never be added to instances
    constructor() {
        return {};
    }
}
# 规则详情
此规则不允许在 return、throw、continue 和 break 语句之后出现无法访问的代码。此规则还标记其构造函数没有 super() 调用的子类中的实例字段定义。
此规则的错误代码示例:
/*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");
由于 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;
}
此规则的其他错误代码示例:
/*eslint no-unreachable: "error"*/
class C extends B {
    #x; // unreachable
    #y = 1; // unreachable
    a; // unreachable
    b = 1; // unreachable
    constructor() {
        return {};
    }
}
此规则的附加正确代码示例:
/*eslint no-unreachable: "error"*/
class D extends B {
    #x;
    #y = 1;
    a;
    b = 1;
    constructor() {
        super();
    }
}
class E extends B {
    #x;
    #y = 1;
    a;
    b = 1;
    // implicit constructor always calls `super()`
}
class F extends B {
    static #x;
    static #y = 1;
    static a;
    static b = 1;
    constructor() {
        return {};
    }
}
