Arrow functions
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
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;
console.log(square(5)); // → 25
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
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.
Common mistakes
x => x + 1is a short function; with no braces it returns the expression.- Arrow functions are handy as arguments to array methods.
Now you try
- Write each arrow function.
- Press Check answer to test it.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Write an arrow function triple that returns its argument times 3: const triple = (n) => n * 3;.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Write an arrow function add with two parameters that returns their sum.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Write an arrow function isEven that returns true when its argument is even (n % 2 === 0).
Click Run to see the output here.