LoginSignup
0
0

More than 1 year has passed since last update.

関数式

Last updated at Posted at 2021-06-04

関数式


関数式の場合は、function(引数) {}という無名の関数を変数に定義または、代入して関数を定義する、と言う記述になります。

変数 = function(引数) {
 //関数内の処理
}

関数宣言と関数式の違いについて


関数宣言と関数式では読み込まれるタイミングが異なります。

以下のコードを実行すると、Uncaught ReferenceError...といった形でエラーが表示されます。

hello()

const hello = function() {
console.log('hello')
}

1行目の時点で関数helloは定義されていないため、エラーとなります。一方、以下のように関数宣言を用いた場合はエラー無く、helloと出力が確認できます。

hello()

function hello(){
 console.log('hello')
}

JavaScriptにおいては関数宣言は先に読み込まれるために、このような事象が発生します。一方で関数式であれば先に読み込まれることはありません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0