1
2

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の「Arrow関数 vs 通常関数」完全理解!現場での使い分け&落とし穴🔥

Posted at

こんにちは!JavaScript歴5年のアミットです💻
「ReactやNode.jsを書いていると、functionと**=>(アロー関数)**、どっちを使うか迷う…」そんな経験ありませんか?

結論から言うと…

✅「両方に向き・不向きがあります」

この記事では、現場のコードでよくあるリアルな例を使って、
Arrow関数と通常関数の違い・使い分け・注意点をわかりやすく解説します!


🎬 まずは基本構文の違いをおさらい!

🔹 通常の関数(Function Declaration)

function greet(name) {
  return `こんにちは、${name}さん!`;
}

🔸 アロー関数(Arrow Function)

const greet = (name) => `こんにちは、${name}さん!`;

✅ シンプル!
✅ 匿名関数やコールバックにぴったり!


🔍 大きな違いは「this」の扱い!

📌 例:クラスの中でのthis

class Counter {
  count = 0;

  // 通常関数
  increment() {
    setTimeout(function () {
      this.count++;
      console.log("通常関数:", this.count); // ❌ undefined またはエラー
    }, 1000);
  }

  // アロー関数
  incrementFixed() {
    setTimeout(() => {
      this.count++;
      console.log("アロー関数:", this.count); // ✅ 正しく this が参照される
    }, 1000);
  }
}

const c = new Counter();
c.increment();       // NG
c.incrementFixed();  // OK

🧠 なぜ?

  • 通常関数:thisは呼び出し元(setTimeout内部)にバインドされる
  • アロー関数:外側のスコープ(クラス)を保持する

🧪 現場でよく使うケース比較

✅ 1. Reactのイベントハンドラー(アロー関数が便利)

const Button = () => {
  const handleClick = () => {
    console.log("✅ ボタンがクリックされました");
  };

  return <button onClick={handleClick}>Click</button>;
};

this を気にせず使える!
➡ ラムダ式的に書けて、読みやすい!


❌ 2. オブジェクトメソッド(通常関数が◎)

const user = {
  name: "アミット",
  greet: function () {
    console.log(`こんにちは、${this.name}`);
  },
};

user.greet(); // ✅ OK
const userArrow = {
  name: "アミット",
  greet: () => {
    console.log(`こんにちは、${this.name}`);
  },
};

userArrow.greet(); // ❌ undefined

❗ アロー関数では this がグローバルになるため、オブジェクトの中では非推奨!


✅ 3. 配列処理(アロー関数が神)

const numbers = [1, 2, 3];
const doubled = numbers.map((n) => n * 2);
console.log(doubled); // [2, 4, 6]

➡ コールバックの中身が短ければ、アローで読みやすく!


🧱 アロー関数の特徴まとめ

特徴 内容
this 親スコープを引き継ぐ
arguments 使用できない(代わりにRest演算子を使う)
new不可 newキーワードでインスタンス化できない
短く書ける 1行処理に向いてる

👀 実務での使い分け早見表

シーン おすすめ関数 理由
Reactの関数コンポーネントやイベント アロー関数 this管理が不要
オブジェクトのメソッド定義 通常関数 thisがオブジェクトを指す
配列のmap/filter/reduceなど アロー関数 短く書けて読みやすい
クラスメソッドでコールバック使用 アロー関数 thisが外に逃げない
コンストラクタ関数として定義 通常関数 アロー関数はnewできない

💣 よくあるミス

const Timer = {
  time: 0,
  start: () => {
    setInterval(() => {
      this.time++;
      console.log(this.time);
    }, 1000);
  },
};

Timer.start(); // ❌ this.time は NaN または undefined

➡ 対策:function() を使う or thisの代わりに let self = this; など


✨ まとめ

比較項目 通常関数 アロー関数
this 呼び出し元によって変わる 定義されたスコープを保持
arguments 使用可能 ❌使用不可
new 可能 ❌不可
書き方 少し冗長 簡潔に書ける
主な用途 オブジェクト/クラスメソッド コールバック/イベント/React関数

🧩 最後に:どっちが正解?

答えは...

🎯 「適材適所」!

  • 「シンプル・thisが不要」なら → アロー関数
  • thisargumentsを使いたい」なら → 通常関数

迷ったらこの早見表をチェックして、適切に使い分けましょう!


📌 Qiitaタグ案

JavaScript アロー関数 関数の違い 初心者向け React this

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?