Missing 返回 语句
快速摘要
你的 函数 calculated 值 但 forgot 到 返回 它 — caller 接收 undefined 相反 的 预期结果.
为什么发生
Computed 值 但 做 不 编写
返回之前 它返回 语句 是 内部 如果-块 那个 做 不 总是 执行
Forgot 到 返回 从 one 分支 的 conditional
最小示例
✗ 错误代码
function double(x) {
x * 2; // Computed but not returned!
}
console.log(double(5)); // undefined✓ 修复代码
function double(x) {
return x * 2; // Now it returns the result
}
console.log(double(5)); // 10不使用 返回, computed 值 是 discarded and 函数 返回 undefined. 添加 返回 发送 值 后面 到 caller.
如何诊断
检查 如果 函数 返回 undefined 当 它 应该 返回 值
Look for calculations 那个 是 不 preceded 通过
返回验证 所有 code paths in conditionals 有 返回 语句
如何修复
添加
返回之前 表达式 那个 应该 是 发送 后面Ensure 所有 分支 的 如果/else 返回 值
添加 默认 返回 at 端 的 函数
如何预防
总是 验证 那个 函数 meant 到 返回 值 有 返回 语句
Use TypeScript 到 catch missing 返回 at 编译 时间