Skip to content
dreamcode
dreamcode
Map
Higher-order
Lesson 26 of 48
+15 XP on finish
JS FUNCTIONSChapter 5 · JS Functions and Classes

Higher-Order Functions

A higher-order function takes a function as an argument, returns one, or both. You already use them: map, filter and forEach all take a function. Writing your own lets you capture a pattern once, such as "do this n times" or "only run this once", and reuse it with any behaviour plugged in.

Worked example

How it reads

  • repeat takes the action as a parameter and calls it
  • once returns a new function that remembers whether it already ran
  • ...args forwards whatever arguments the caller passes
Cloud tip: When two functions differ only in one small step, pass that step in as a function.
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Write applyTwice(fn, x) that returns fn(fn(x)), then print applyTwice((n) => n * 3, 2): 18.

Press Run to check your work.