Higher-Order Functions
Functions as values.
In JavaScript, functions are values. You can store them in variables, pass them to other functions, and return them. A function that takes or returns another function is called a higher order function. You've already used them, like map and filter.

- Functions are values
- Pass them, return them
- map and filter already
Making functions
Multiplier takes a number, and returns a new function that multiplies by it. So double and triple are both functions, each remembering its own number, thanks to closures. Repeat takes a function, and calls it several times. Run it.
function multiplier(factor) {
return (n) => n * factor;
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(5), triple(5));
function repeat(times, action) {
for (let i = 1; i <= times; i++) action(i);
}
repeat(3, (i) => console.log("Round", i));10 15 Round 1 Round 2 Round 3
A tiny pipeline
Compose takes several functions, and returns one function that runs them in order, passing each result on. Reduce does the work. This idea, building programs from small functions, is the heart of functional programming. Run it.
const compose = (...fns) => (x) => fns.reduce((value, fn) => fn(value), x);
const trim = (s) => s.trim();
const lower = (s) => s.toLowerCase();
const slug = (s) => s.replaceAll(" ", "-");
const makeSlug = compose(trim, lower, slug);
console.log(makeSlug(" Learn JavaScript Today "));learn-javascript-today
Summary
Functions are values you can pass and return. Higher order functions like map, filter, and compose let you build programs from small pieces. Next, debugging.
Key takeaways- Functions are values
- Return functions
- Pass functions in