newline-before-return
return
语句前需要一个空行
此规则报告的一些问题可通过 --fix
命令行选项自动修复
该规则在 ESLint v4.0.0 中已弃用,并由 padding-line-between-statements 规则取代。
¥This rule was deprecated in ESLint v4.0.0 and replaced by the padding-line-between-statements rule.
关于 JavaScript 中的 return
语句之前是否应该有空行,并没有硬性规定。但是,清楚地描述函数返回的位置可以大大提高代码的可读性和清晰度。例如:
¥There is no hard and fast rule about whether empty lines should precede return
statements in JavaScript. However, clearly delineating where a function is returning can greatly increase the readability and clarity of the code. For example:
function foo(bar) {
var baz = 'baz';
if (!bar) {
bar = baz;
return bar;
}
return bar;
}
添加换行符明显地将 return 语句与前几行分开,明确函数退出的位置以及它返回的值:
¥Adding newlines visibly separates the return statements from the previous lines, making it clear where the function exits and what value it returns:
function foo(bar) {
var baz = 'baz';
if (!bar) {
bar = baz;
return bar;
}
return bar;
}
规则详情
¥Rule Details
此规则要求 return
语句之前有一个空行以增加代码清晰度,除非 return
单独位于语句组中(例如 if 语句)。在后一种情况下,return
语句不需要单独描述。注释被忽略,不计为空行。
¥This rule requires an empty line before return
statements to increase code clarity, except when the return
is alone inside a statement group (such as an if statement). In the latter case, the return
statement does not need to be delineated by virtue of it being alone. Comments are ignored and do not count as empty lines.
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint newline-before-return: "error"*/
function foo1(bar) {
if (!bar) {
return;
}
return bar;
}
function foo2(bar) {
if (!bar) {
return;
}
/* multi-line
comment */
return bar;
}
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint newline-before-return: "error"*/
function foo1() {
return;
}
function foo2() {
return;
}
function foo3(bar) {
if (!bar) return;
}
function foo4(bar) {
if (!bar) { return };
}
function foo5(bar) {
if (!bar) {
return;
}
}
function foo6(bar) {
if (!bar) {
return;
}
return bar;
}
function foo7(bar) {
if (!bar) {
return;
}
}
function foo8() {
// comment
return;
}
何时不使用
¥When Not To Use It
如果你对 return
语句之前的空格没有任何严格的约定,你可以安全地禁用此规则。
¥You can safely disable this rule if you do not have any strict conventions about whitespace before return
statements.
相关规则
版本
此规则是在 ESLint v2.3.0 中引入。