Functions
Functions as values
A function is a value just like a number or a string: it can be stored, passed and returned.
Why it exists
Often you need to pass not data but behaviour: "what to do with each item" (map), "by what rule to select" (filter), "what to run when the response arrives" (then), "what to do on click" (onClick). If functions are ordinary values, one mechanism covers all of it: you pass the function to where it will be called.
Where it's used
Syntax
const f = (x) => x * 2; // in a variable
[1, 2].map(f); // as an argument
function make() {
return () => "hello"; // as a result
}Examples
const double = (n) => n * 2;
[1, 2, 3].map(double); // → [2, 4, 6]const isEven = (n) => n % 2 === 0;
[1, 2, 3, 4].filter(isEven); // → [2, 4]filterfunction twice(fn, x) {
return fn(fn(x));
}
twice((n) => n + 10, 1); // → 21const add = (a) => (b) => a + b;
add(2)(3); // → 5Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
A declaration function f() {} or an arrow () => … creates a value of type "function". The function's name is just a variable that refers to it.
To pass a function, write its name without parentheses: map(double). With parentheses, double() would call it now and pass the result.
A callback is a function handed to another function so that function can call it later. The receiving function decides who calls it and when.
You can return a function from a function just like a number. The variables it closed over travel with it — that's how function factories work.
Traps
How it differs from…
- Closure
A returned function remembers the variables of the place it was created — that's a closure.
- Arrow functions
Arrows are the shortest way to write callbacks and returned functions.
When to pick something else
Don't wrap everything in higher-order functions for elegance: a chain of five nested compose(…) reads worse than a simple loop. Pass functions where it genuinely makes the code simpler.