AI Hints
Home›JavaScript Tutorial›Sets, Maps and Regex
JavaScript · Lesson 111 of 138

Higher-Order Functions

Functions as values.

⏱ 2 min read▶ Video at 2:13:38🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Higher-Order Functions
From the video: Higher-Order Functions
  • 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.

app.jsjavascript
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));
Output
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.

app.jsjavascript
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 "));
Output
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
Next up: Debugging — finding bugs fast