Functions · Lesson 18 of 45
Callbacks and higher-order functions
Functions that take functions: the basis of map, filter and events.
8 minutes3 games
In JavaScript functions are values like numbers and strings: store them, pass them to other functions, return them. A function handed to another function to call later is a callback; the function that takes it is a higher-order function.
JavaScript
function repeat(times, action) {
for (let i = 1; i <= times; i++) action(i)
}
repeat(3, (n) => console.log("Hello", n))
const shout = (text) => text.toUpperCase() + "!"
const whisper = (text) => text.toLowerCase() + "…"
function say(text, style) {
return style(text)
}
console.log(say("Hi", shout))
console.log(say("Hi", whisper))You pass action
repeat calls it 3 times
each time with its number
What's the output?
function apply(x, fn) {
return fn(x)
}
console.log(apply(4, (n) => n + 1))What will this code print?
Spot the bug
greet should be called 3 times. Which line has the mistake?
Exercise
Write applyTwice(fn, x) that returns fn(fn(x)). Print applyTwice((n) => n * 3, 2) (18).
Expected output: 18
JavaScript
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.