javascript · level 3 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A noisy wrapper. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function logged(task) {
return (x) => {
console.log(`calling with ${x}`);
return task(x);
};
}
const double = (n) => n * 2;
const loudDouble = logged(double);
console.log(loudDouble(4));
console.log(double(5));
your turn
Your turn. Make a filter with a built-in limit.
olderThan returns a function that filter can use. Choose an age limit between 13 and 34, so 35 and 70 get through but 12 does not.
fix it
The wrapper loses the answer. Can you fix it?
- The message appears, then
undefined. What does the wrapper hand back? task(x)works out 36, but the wrapper throws the answer away instead of passing it on.- On line 4, write
return task(x);, then press run.
nailed it
you built functions that build functions. :D
- Higher-order functions take or return other functions.
- A wrapper adds behaviour without changing the original.
- A wrapper must return the original's answer.
new words in your collection
- higher-order function
- wrapper
This lesson isn’t saved. A free account remembers every lesson you finish.