傳回關鍵字

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

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