Higher-Order Functions

Functions That Take or Return Functions

Example

map, filter and reduce are higher-order functions. You can write your own:

const repeat = (n, action) => { for (let i = 0; i < n; i++) action(i); };
repeat(3, (i) => console.log("step", i));

const unless = (test, then) => { if (!test) then(); };
unless(5 > 10, () => console.log("5 is not greater than 10"));

const logged = (fn) => (...args) => {
  const result = fn(...args);
  console.log(`${fn.name}(${args}) = ${result}`);
  return result;
};
const max = logged(Math.max);
max(3, 9, 4);

Output

step 0
step 1
step 2
5 is not greater than 10
max(3,9,4) = 9