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-02-04

1. アロー関数とは?

アロー関数(Arrow Function)は、JavaScript ES6 で導入された関数の記法で、 従来の function キーワードを使った記述より 短く、直感的 に書けるのが特徴です。

// 従来の関数記法
function add(a, b) {
    return a + b;
}

// アロー関数記法
const add = (a, b) => a + b;

ポイント=>(アロー)を使って関数を定義する。


2. アロー関数の基本構文

const 関数名 = (引数1, 引数2, ...) => ;

☑️ 例1:通常のアロー関数

const greet = (name) => `こんにちは、${name}!`;
console.log(greet("太郎")); // 出力: こんにちは、太郎!

3. 引数の扱い

☑️ 例2:引数が1つの場合、() を省略できる

const square = x => x * x;
console.log(square(4)); // 出力: 16

☑️ 例3:引数が複数ある場合、() が必要

const multiply = (a, b) => a * b;
console.log(multiply(3, 5)); // 出力: 15

4. ブロック構文と {} の省略ルール

☑️ 例4:複数の文を処理する場合、 {} を使用し、return を明示的に記述する必要がある。

const addAndLog = (a, b) => {
    const sum = a + b;
    console.log(`合計: ${sum}`);
    return sum;
};
console.log(addAndLog(3, 7));

☑️ 例5:単一の式では {}return を省略可能

const add = (a, b) => a + b;
console.log(add(3, 7));

{} を省略できる条件:関数の処理が 1行かどうかではなく、単一の式であること
{} を使うと ブロック文 になるため、return を明示的に書く必要がある。

☑️ 例6:オブジェクトを返す場合の注意

const getUser = () => {
   return { name: "太郎", age: 25 };
};
console.log(getUser());

オブジェクトを返す場合、{} を使うとブロック扱いになるため return が必要だが、 () で囲めば return を省略できる。

const getUser = () => ({ name: "太郎", age: 25 });
console.log(getUser());

5. this の挙動

アロー関数の最大の特徴のひとつは、this のバインドが変わらないことです。

☑️ 例7:this の挙動(通常の関数)

function Person(name) {
    this.name = name;
    this.sayHello = function() {
        setTimeout(function() {
            console.log(`こんにちは、${this.name}!`);
        }, 1000);
    };
}

const person = new Person("太郎");
person.sayHello(); // `this.name` が `undefined` になる

理由setTimeout 内の function新しい this を持つため

☑️ 例8:アロー関数を使った場合

function Person(name) {
    this.name = name;
    this.sayHello = function() {
        setTimeout(() => {
            console.log(`こんにちは、${this.name}!`);
        }, 1000);
    };
}

const person = new Person("太郎");
person.sayHello(); // 正しく「こんにちは、太郎!」と表示される

ポイント:アロー関数は 外側の this を継承 するため、意図した動作になる。


6. まとめ

☑️ アロー関数は => を使って定義できる
☑️ () の省略が可能(引数1つのとき)
☑️ {} を使うと複数行の処理が可能
☑️ this の挙動が通常の関数と異なり、外側の this を引き継ぐ
☑️ オブジェクトを返す場合、() で括ると return を省略できる

アロー関数を使いこなして、シンプルで可読性の高いコードを書こう!

0
0
4

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?