Functions
Arrow functions
A short way to write a function with =>, used mostly for callbacks.
Why it exists
Many methods take a function as an argument: map, filter, sort, click handlers, setTimeout. These functions are usually tiny — "take the price", "keep the even ones". Writing function (x) { return x * 2; } for them is a lot of noise around one idea. An arrow function (x) => x * 2 keeps only the point, so code with callbacks reads like a description: "filter the adults, take their names".
Where it's used
- Callbacks for array methods:
prices.map((p) => p * 1.2). - Event handlers in React:
onClick={() => setOpen(true)}. - Short helpers:
const isEmpty = (s) => s.trim() === "". - Sorting:
users.sort((a, b) => a.age - b.age).
Syntax
(param) => expression
(a, b) => {
return ...;
}Examples
const double = (x) => x * 2;
double(4); // → 8
const wrong = (x) => { x * 2 };
wrong(4); // → undefined — no returnconst prices = [100, 250, 40];
prices.map((p) => p * 2); // → [200, 500, 80]
prices.filter((p) => p > 50); // → [100, 250]const toUser = (name) => ({ name, active: true });
toUser("Ann"); // → { name: "Ann", active: true }const add = (a, b) => {
const sum = a + b;
return sum;
};
add(2, 3); // → 5returnResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Parameters go left of =>, the body goes right. If the body is one expression without braces, its value is returned automatically (an "implicit return"). Add braces and it becomes a block of code, and the only way to return a value is an explicit return.
A single parameter can go without parentheses (x => x * 2), but keeping them is more consistent. With no parameters they're required: () => 42.
Arrow functions arrived in 2015 (the ES6 standard). They also have a technical difference: they have no this of their own and take it from outside — which makes them handy inside methods and handlers.