警告:return 语句后无法访问代码

当在 return 语句之后使用表达式时,或者使用无分号的 return 语句但在其后直接包含表达式时,会出现 JavaScript 警告 "return 语句后无法访问代码"。

¥The JavaScript warning "unreachable code after return statement" occurs when using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after.

信息

¥Message

Warning: unreachable code after return statement (Firefox)

错误类型

¥Error type

警告

¥Warning

什么地方出了错?

¥What went wrong?

在以下情况下,可能会出现 return 语句后无法访问的代码:

¥Unreachable code after a return statement might occur in these situations:

  • 当在 return 语句后使用表达式时,或者
  • 当使用无分号的 return 语句但在其后直接包含表达式时。

当有效的 return 语句后面存在表达式时,会发出警告,指示 return 语句后面的代码无法访问,这意味着它永远无法运行。

¥When an expression exists after a valid return statement, a warning is given to indicate that the code after the return statement is unreachable, meaning it can never be run.

为什么 return 语句后面应该有分号?对于无分号 return 语句,可能不清楚开发者是否打算返回下一行的语句,或者停止执行并返回。该警告表明 return 语句的编写方式存在歧义。

¥Why should I have semicolons after return statements? In the case of semicolon-less return statements, it can be unclear whether the developer intended to return the statement on the following line, or to stop execution and return. The warning indicates that there is ambiguity in the way the return statement is written.

如果后面有以下语句,则不会针对无分号返回显示警告:

¥Warnings will not be shown for semicolon-less returns if these statements follow it:

示例

¥Examples

无效案例

¥Invalid cases

js
function f() {
  let x = 3;
  x += 4;
  return x;   // return exits the function immediately
  x -= 3;     // so this line will never run; it is unreachable
}

function g() {
  return     // this is treated like `return;`
    3 + 4;   // so the function returns, and this line is never reached
}

有效案例

¥Valid cases

js
function f() {
  let x = 3;
  x += 4;
  x -= 3;
  return x; // OK: return after all other statements
}

function g() {
  return 3 + 4 // OK: semicolon-less return with expression on the same line
}

也可以看看

¥See also