傳回關鍵字

使用 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 的用途為何?

將程式碼傳回函式的開頭。
指定函式的最終結果。