×

javascript · level 3 · unit 1 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A takes or returns other functions.

map and filter take a function as an argument, so each is a higher-order function. You can write your own. Combined with closures, they let you upgrade any function without touching its code.

once below takes a function and returns a : a new function that calls the original the first time, then remembers the answer and never runs it again. Handy for a payment button that must never charge twice.

function once(task) {
  let done = false;
  let result;
  return (...args) => {
    if (!done) {
      result = task(...args);
      done = true;
    }
    return result;
  };
}
const pay = once((amount) => { console.log(`Charging £${amount}`); return "paid"; });
console.log(pay(30));
console.log(pay(30));

...args gathers every argument into an array, and task(...args) spreads them back out.