no-else-return
禁止在 if 语句中的 return 语句后出现 else 代码块
如果 if 代码块包含 return 语句,则 else 代码块变得不必要。其内容可以放在代码块之外。
function foo() {
if (x) {
return y;
} else {
return z;
}
}
规则详情
此规则旨在突出显示包含 return 语句的 if 之后的非必要代码块。因此,当它遇到跟随一系列 if 语句的 else 时,会发出警告,所有 if 语句都包含 return 语句。
选项
此规则具有对象选项
allowElseIf: true(默认) 允许在return之后使用else if代码块allowElseIf: false禁止在return之后使用else if代码块
allowElseIf: true
此规则的错误代码示例
在 Playground 中打开
/*eslint no-else-return: "error"*/
function foo1() {
if (x) {
return y;
} else
}
function foo2() {
if (x) {
return y;
} else if (z) {
return w;
} else
}
function foo3() {
if (x) {
return y;
} else
return t;
}
function foo4() {
if (error) {
return 'It failed';
} else
}
// Two warnings for nested occurrences
function foo5() {
if (x) {
if (y) {
return y;
} else
} else
}
此规则的正确代码示例
在 Playground 中打开
/*eslint no-else-return: "error"*/
function foo1() {
if (x) {
return y;
}
return z;
}
function foo2() {
if (x) {
return y;
} else if (z) {
var t = "foo";
} else {
return w;
}
}
function foo3() {
if (x) {
if (z) {
return y;
}
} else {
return z;
}
}
function foo4() {
if (error) {
return 'It failed';
} else if (loading) {
return "It's still loading";
}
}
allowElseIf: false
此规则的错误代码示例
在 Playground 中打开
/*eslint no-else-return: ["error", {allowElseIf: false}]*/
function foo() {
if (error) {
return 'It failed';
} else
}
此规则的正确代码示例
在 Playground 中打开
/*eslint no-else-return: ["error", {allowElseIf: false}]*/
function foo() {
if (error) {
return 'It failed';
}
if (loading) {
return "It's still loading";
}
}
版本
此规则在 ESLint v0.0.9 中引入。