return 关键字

使用 return 来指定函数应生成的最终结果值。当解释器遇到 return 语句时,包含该语句的函数会立即结束,并将指定的值返回到调用该函数的上下文

const myFunction = function() {
   return 2 + 2;
}

myFunction();
> 4

返回值的函数可以有效地视为其包含的数据,类似于变量

const myFunction = function() {
   return 2 + 2;
}

myFunction() + myFunction();
> 8

不带表达式的 return 语句会结束函数并返回 undefined

const myFunction = function() {
   return;
}

myFunction();
> undefined

由于 return 关键字表示函数结束,因此在遇到 return 后面的任何代码都不会执行

const myFunction = function() {
   return true;
   console.log( "This is a string." );
}

myFunction();
> true

此外,在某些浏览器的开发人员控制台中,在遇到 return 语句后面的代码可能会导致警告(但不是错误)

const myFunction = function() {
   return true;
   console.log( "This is a string." );
}
> unreachable code after return statement

myFunction();
> true

同样,这仅适用于在函数执行期间遇到的 return 语句,而不适用于按顺序在 return 语句后面的任何代码

const myFunction = function( myParameter ) {
   if( myParameter === undefined ) {
    return "This is the result.";
   }
   return "This is the alternate result.";
}

myFunction();
> "This is the result."

myFunction( true );
> "This is the alternate result."

与函数末尾的单个 return 语句相比,使用提前 return “短路”函数可以使代码更简洁。例如,以下函数确定传递的值是否是包含五个或更多字符的字符串。如果传递的值不是字符串字面量,则计算字符数的代码是不必要的,并且该函数可以立即返回 false 结果

function myFunction( myString ) {
   if( typeof myString !== "string" ) {
    return false;
   }
   if( myString.length >= 5 ) {
    return true;
   } else {
    return false;
   }
}

myFunction( 100 );
> false

myFunction( "St" );
> false

myFunction( "String." );
> true

箭头函数表达式的独特之处在于,当箭头函数体包含单个表达式且没有块语法时,return 关键字是隐含的

const myFunction = () => 2 + 2;

myFunction();
> 4

如果您使用块语法来定义箭头函数体,则即使函数体仅包含单个表达式,也需要显式的 return

const myFunction = () => { 2 + 2 };

myFunction();
> undefined
const myFunction = () => { return 2 + 2 };

myFunction();
> 4

检查您的理解情况

return 用于做什么?

指定函数的最终结果。
将代码返回到函数的开头。