Warning: unreachable code after return statement

JavaScript 警告“return 语句后的代码无法访问”发生在 return 语句后使用了表达式,或者使用了不带分号的 return 语句但直接在其后包含了一个表达式。

消息

Warning: unreachable code after return statement (Firefox)

错误类型

警告

哪里出错了?

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

  • return 语句后使用了表达式,或者
  • 使用了不带分号的 return 语句但直接在其后包含了一个表达式。

当一个有效的 return 语句后存在表达式时,会发出警告,表明 return 语句后的代码无法访问,这意味着它永远不会被执行。

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

如果以下语句紧随其后,则不会显示不带分号的 return 的警告:

示例

无效案例

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
}

有效情况

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
}

另见