Closures and functions as values
In JavaScript, functions are values, like numbers and strings. You can store them in variables, pass them to other functions, and return them:
const shout = text => text.toUpperCase() + "!";
function twice(fn, value) {
return fn(fn(value));
}
twice(x => x + 3, 1); // 7
You have already done this: map, filter and reduce take functions as arguments. Functions that take or return functions are called higher-order functions.
Closures
A function remembers the variables that existed where it was created, even after that outer function has finished. This is a closure:
function makeGreeter(greeting) {
return name => `${greeting}, ${name}!`;
}
const hello = makeGreeter("Hello");
const mhoro = makeGreeter("Mhoro");
hello("Ana"); // "Hello, Ana!"
mhoro("Tino"); // "Mhoro, Tino!"
Each returned function keeps its own greeting. Closures are how JavaScript keeps private state: nothing outside can reach greeting except through the function.
Your task
makeCounter()returns a function. Each call to that function returns the next number: 1, then 2, then 3... Each counter keeps its own count.compose(f, g)returns a new function that, givenx, returnsf(g(x)).once(fn)returns a function that callsfnthe first time only, and on every later call returns the first result without callingfnagain.