return
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
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
キーワードと式の間の改行コードは許容されません。
return
a + b;
上記のコードは ASI によって以下のように変換されます。
return;
a + b;
コンソールは "unreachable code after return statement" と警告します。
メモ:
Firefox 40 以降から return
文の後に到達不可能なコードが見つかった場合、コンソールに警告が表示されます。
括弧を使用することで、この問題を回避する(ASI を防ぐ)ことができます。
return (
a + b
);
例
関数を中断する
関数は 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
仕様書
Specification |
---|
ECMAScript® 2025 Language Specification # sec-return-statement |
ブラウザーの互換性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
return |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support