A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/return below:

return - JavaScript | MDN

return

Baseline Widely available

return 文は関数の実行を終了して、関数の呼び出し元に返す値を指定します。

試してみましょう
function getRectArea(width, height) {
  if (width > 0 && height > 0) {
    return width * height;
  }
  return 0;
}

console.log(getRectArea(3, 4));
// Expected output: 12

console.log(getRectArea(-3, 4));
// Expected output: 0
構文
return;
return expression;
expression

値が返される式。省略した場合は、代わりに undefined が返されます。

解説

return 文が関数本体の中で使用された際、その関数の実行が停止します。値を指定した場合、与えられた値が関数の呼び出し元に返されます。例として、以下の関数は引数 x が数値のとき、x の二乗を返します。

function square(x) {
  return x * x;
}
const demo = square(3);
// demo は 9 に等しい

値が省略された場合は、代わりに undefined が返されます。

以下の return 文はすべて関数の実行を中断するものです。

return;
return true;
return false;
return x;
return x + y / 3;
自動セミコロン挿入

return 文は自動セミコロン挿入 (ASI) の影響を受けます。return キーワードと式の間の改行コードは許容されません。

上記のコードは ASI によって以下のように変換されます。

コンソールは "unreachable code after return statement" と警告します。

メモ: Firefox 40 以降から return 文の後に到達不可能なコードが見つかった場合、コンソールに警告が表示されます。

括弧を使用することで、この問題を回避する(ASI を防ぐ)ことができます。

例 関数を中断する

関数は return が呼び出された時点で即座に終了します。

function counter() {
  // 無限ループ
  for (let count = 1; ; count++) {
    console.log(`${count}A`); // 5 まで
    if (count === 5) {
      return;
    }
    console.log(`${count}B`); // 4 まで
  }
  console.log(`${count}C`); // 決して現れない
}

counter();

// ログ:
// 1A
// 1B
// 2A
// 2B
// 3A
// 3B
// 4A
// 4B
// 5A
関数を返す

クロージャについての記事も参照のこと。

function magic() {
  return function calc(x) {
    return x * 42;
  };
}

const answer = magic();
answer(1337); // 56154
仕様書 ブラウザーの互換性 関連情報

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4