関数宣言(関数文)は、指定されたパラメーターを使用して関数を定義します。
また、関数のコンストラクターと関数式を使用して関数を定義することもできます。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
構文
function name([param[, param,[..., param]]]) {
[statements]
}
name- 関数の名前です。
paramOptional- 関数に渡す引数の名前です。引数の最大数はエンジンによって異なります。
statementsOptional- 関数の本体を構成する文です。
説明
関数宣言で作成された関数は、Function オブジェクトであり、Function オブジェクトのすべてのプロパティ、メソッド、動作を備えています。Function の詳細については Function を参照してください。
関数は式を使用して作成することもできます。(関数式を参照)
既定では、関数は undefined を返します。他の値を返すには、関数に返す値を指定する return 文が必要です。
条件付きの関数を作成する
関数は条件付きで宣言できます。つまり、関数文を if 文の中に入れ子にすることができますが、結果は実装によって一貫性がないので、このパターンを本番コードでは使用すべきではありません。条件付きの関数の作成には、代わりに関数式を使用してください。
var hoisted = "foo" in this;
console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);
if (false) {
function foo(){ return 1; }
}
// In Chrome:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Firefox:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Edge:
// 'foo' name is not hoisted. typeof foo is undefined
//
// In Safari:
// 'foo' name is hoisted. typeof foo is function
真と評価される条件でも結果はまったく同じです。
var hoisted = "foo" in this;
console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);
if (true) {
function foo(){ return 1; }
}
// In Chrome:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Firefox:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Edge:
// 'foo' name is not hoisted. typeof foo is undefined
//
// In Safari:
// 'foo' name is hoisted. typeof foo is function
関数宣言の巻き上げ
JavaScript の関数宣言は、それを囲む関数やグローバルスコープの先頭に巻き上げられ、関数を宣言する前に使うことができます。
hoisted(); // logs "foo"
function hoisted() {
console.log('foo');
}
関数式は巻き上げられないことに注意してください。
notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function() {
console.log('bar');
};
例
function を使用する
以下のコードは、商品 a, b, c の販売個数が与えられた場合に、販売個数の合計を返す関数を宣言しています。
function calc_sales(units_a, units_b, units_c) {
return units_a * 79 + units_b * 129 + units_c * 699;
}
仕様
| 仕様書 |
|---|
| ECMAScript (ECMA-262) Function definitions の定義 |
ブラウザー実装状況
| デスクトップ | モバイル | サーバー | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
function | Chrome 完全対応 1 | Edge 完全対応 12 | Firefox 完全対応 1 | IE 完全対応 3 | Opera 完全対応 3 | Safari 完全対応 1 | WebView Android 完全対応 1 | Chrome Android 完全対応 18 | Firefox Android 完全対応 4 | Opera Android 完全対応 10.1 | Safari iOS 完全対応 1 | Samsung Internet Android 完全対応 1.0 | nodejs 完全対応 0.1.100 |
| Trailing comma in parameters | Chrome 完全対応 58 | Edge 完全対応 14 | Firefox 完全対応 52 | IE 未対応 なし | Opera 完全対応 45 | Safari 完全対応 10 | WebView Android 完全対応 58 | Chrome Android 完全対応 58 | Firefox Android 完全対応 52 | Opera Android 完全対応 43 | Safari iOS 完全対応 10 | Samsung Internet Android 完全対応 7.0 | nodejs 完全対応 8.0.0 |
凡例
- 完全対応
- 完全対応
- 未対応
- 未対応