0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptの関数定義

Last updated at Posted at 2025-11-08

🟩 1. 関数宣言(Function Declaration)

function func1(str) {
  return str;
}

🔍 特徴

最も基本的で昔からある書き方。

「関数宣言」 と呼ばれます。

巻き上げ(Hoisting) が行われるため、
定義より前で呼び出しても動作します。

例:

console.log(func1("Hello")); // ✅ OK

function func1(str) {
  return str;
}

このように、スクリプトを実行する際に関数が先にメモリに読み込まれるため、後ろで定義しても呼び出せます。

🟦 2. 関数式(Function Expression)

const func1 = function (str) {
  return str;
};

🔍 特徴

変数に関数を代入する書き方。

この場合、関数は「無名関数(anonymous function)」として扱われます。

巻き上げされないので、定義前に呼ぶとエラーになります。

例:

func1("Hello"); // ❌ エラー: Cannot access 'func1' before initialization

const func1 = function (str) {
  return str;
};

💡 利点

変数に関数を代入するので、コールバック関数などに使いやすい。

他の関数の中で定義して渡すことも容易。

🟨 3. 2015年(ES6)以降に追加されたもの

参考までに — ES2015 で登場した「アロー関数」:

const func1 = (str) => {
  return str;
};

こちらは「関数式」の一種で、より短く書ける新しい構文です。

✅ まとめ

種類書き方巻き上げ用途・特徴関数宣言function func(){}ありどこからでも呼び出せる関数式const func = function() {};なしコールバックなど柔軟に使えるアロー関数(ES6〜)const func = () => {};なし短く書ける・thisを束縛しない

どちらを使えばいい?という場合は:
👉 モジュール的なコードや現代の開発では「関数式(+アロー関数)」が主流。

0
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?