関数宣言
試してみましょう
構文
function name([param[, param,[..., param]]]) { [statements] }
name
-
関数の名前です。
param
省略可-
関数に渡す引数の名前です。引数の最大数はエンジンによって異なります。
statements
省略可-
関数の本体を構成する文です。
解説
条件付きで作成される関数
関数は条件付きで宣言できます。つまり、関数文を 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;
}
仕様書
Specification |
---|
ECMAScript Language Specification # sec-function-definitions |
ブラウザーの互換性
BCD tables only load in the browser