Arrow functions
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · このページには最新のブラウザ(SharedArrayBuffer対応)が必要です。Chrome、Edge、Firefox、Safariを最新バージョンに更新してください。
English
Arrow functions
- A shorter way to write a function:
const square = (n) => n * n;. - With a single expression after
=>, the value is returned automatically — noreturn, no{ }.
日本語
アロー関数
- 関数を簡潔に書く方法:
const square = (n) => n * n;。 =>の後に単一の式がある場合、自動的に値が返され、returnも{ }も不要です。
const square = (n) => n * n;
console.log(square(5)); // → 25
English
More than one parameter
- List the parameters in the brackets, separated by commas.
日本語
複数のパラメータ
- パラメータをカンマで区切って括弧内にリストアップします。
const add = (a, b) => a + b;
console.log(add(3, 4)); // → 7
English
Watch out
- Need a longer body? Use
{ }and then you must writereturnyourself. - Arrow functions shine as short helpers — you will hand them to
.mapand.filterwhen we reach array methods.
日本語
注意
- 長めのループが必要なら、
{ }を使用し、その後にreturnを自分で記述する必要があります。 - アロー関数は短い補助関数として優秀です。配列メソッドに触れた際、
.mapや.filterに渡すことになります。
English
Common mistakes
x => x + 1is a short function; with no braces it returns the expression.- Arrow functions are handy as arguments to array methods.
日本語
よくあるミス
x => x + 1は短縮された関数であり、波括弧がない場合、式の値が返されます。- アロー関数は配列メソッドの引数として便利です。
English
Now you try
- Write each arrow function.
- Press Check answer to test it.
日本語
あなたも試してみよう
- 各アロー関数を記述してください。
- Check answer を押して確認する。
Write an arrow function triple that returns its argument times 3: const triple = (n) => n * 3;.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Write an arrow function add with two parameters that returns their sum.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Write an arrow function isEven that returns true when its argument is even (n % 2 === 0).
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。