Home › Learn › JavaScript › Functions in depth

Functions as values

Lesson 33 of 40. Pass functions in, get functions out.

Functions are values: they can be stored, passed as arguments, and returned. A function that takes or returns a function is called higher-order; map, filter, and sort are examples, and you can write your own. applyTwice(fn, x) calls fn on x and then on the result.

Returning a function is how you build specialized versions of a general one: multiplier(3) returns a function that multiplies by three. compose(f, g) returns a function that applies g and then f. These patterns show up everywhere in JavaScript libraries.

const twice = (fn, x) => fn(fn(x));
console.log(twice((n) => n + 3, 10));   // 16

const add = (a) => (b) => a + b;
const add5 = add(5);
console.log(add5(2));                   // 7

Your task

Write applyTwice(fn, x) returning fn(fn(x)), multiplier(factor) returning a function that multiplies its argument by the factor, and compose(f, g) returning a function that applies g first and then f.

Hint 1

return fn(fn(x));

Hint 2

return (n) => n * factor; and return (x) => f(g(x));

Show the solution
function applyTwice(fn, x) {
  return fn(fn(x));
}

function multiplier(factor) {
  return (n) => n * factor;
}

function compose(f, g) {
  return (x) => f(g(x));
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.