function記法と違って、以下のような記法で書くような書き方になります。
() => { return "some value"; } () => "some value"
例)
// One line const arrowFunction = () => "return value"; console.log(arrowFunction()); // "return value" const arrowFunction2 = () => { const returnValue = "123"; return returnValue; } console.log(arrowFunction2()); // "123"
定数や変数に関数を代入して、その関数を定数から呼び出すケースが多いです。
最近ではfunctionタイプよりもアロー関数記法のほうが多く使われるため、関数を宣言する際にはアロー関数メインで書くことがおすすめです。(一部、function記法ベースで書くようなプロジェクトもあります)
厳密には違いますが、functionタイプと記法が違うだけで大きくは違いません。
※ functionタイプは呼び出す後に定義しても呼び出せますが、アロー関数の場合はそれが難しい、など
基本的には関数をアロー関数宣言で多く書いていれば慣れてきます。
最初は書き方が独特なので難しく感じますが、使っていると慣れてきます。
コピペではなく実際に打ち込んで練習してみましょう。
実際に手打ちで真似してみましょう。
const arrowFunction = () => "return value"; console.log(arrowFunction()); // return value const arrowFunction2 = () => 123; console.log(arrowFunction2()); // 123 const arrowFunction3 = () => true; console.log(arrowFunction()); // true const arrowFunction4 = () => ({ name: "John" }); console.log(arrowFunction4()); // { name: "John" }
const greet = (name) => `Hello, ${name}!`; console.log(greet("Alice")); // Hello, Alice! const square = (x) => x * x; console.log(square(4)); // 16 const isEven = (num) => num % 2 === 0; console.log(isEven(5)); // false const toUpperCase = (str) => str.toUpperCase(); console.log(toUpperCase("hello")); // HELLO
const sayHello = () => { const greeting = "Hello!"; console.log(greeting); }; sayHello(); // Hello! const getDateInfo = () => { const now = new Date(); const year = now.getFullYear(); const month = now.getMonth() + 1; const day = now.getDate(); return `${year}-${month}-${day}`; }; console.log(getDateInfo()); // 2025-4-5(※実行日によって変わります) const logNumbers = () => { for (let i = 1; i <= 3; i++) { console.log(i); } }; logNumbers(); // 1 // 2 // 3
const greet = name => { const greeting = `Hello, ${name}!`; console.log(greeting); return greeting; }; greet("Taro"); // Hello, Taro! const multiply = (a, b) => { const result = a * b; console.log(`Result is ${result}`); return result; }; multiply(3, 5); // Result is 15 const getUserInfo = user => { const { name, age } = user; return `Name: ${name}, Age: ${age}`; }; console.log(getUserInfo({ name: "Hanako", age: 25 })); // Name: Hanako, Age: 25 const sumArray = arr => { let sum = 0; for (let num of arr) { sum += num; } return sum; }; console.log(sumArray([1, 2, 3, 4])); // 10
このページの例を真似して、自分で5個ぐらいアロー関数を定義して実行してみましょう。