Skip to content
Codewilds

Lesson 12 of 34 · Functions

JavaScript Callbacks and Higher-Order Functions

medium20 XP3 min read

You know that functions are values: you can store them in variables and return them from other functions. The next step is passing a function into another function. This one idea is behind array methods like map and filter, timers, event listeners and promises.

Callbacks

A callback is a function you pass as an argument to another function, so that function can call it later:

function levelUp(level, notify) {
  const newLevel = level + 1;
  notify(`You reached level ${newLevel}!`);
  return newLevel;
}

levelUp(4, (message) => console.log(message));
// You reached level 5!
levelUp(9, (message) => console.log(`*** ${message.toUpperCase()} ***`));
// *** YOU REACHED LEVEL 10! ***

levelUp doesn't know or care how you want to be notified. It just calls whatever function you give it. Swap in a different callback and the same levelUp behaves differently. That's the power of callbacks: the what is separated from the when.

Higher-order functions

A higher-order function is a function that takes a function as an argument, returns a function, or both. You've already written the second kind: makeCounter from the last lesson returns a function.

Here's a higher-order function that takes one:

function doTwice(action) {
  action();
  action();
}

doTwice(() => console.log("Attack!"));
// Attack!
// Attack!

And one that uses the callback's return value:

function transform(value, fn) {
  return fn(value);
}

console.log(transform(5, (n) => n * 10));           // 50
console.log(transform("orc", (s) => s.toUpperCase())); // ORC

Callbacks that answer questions

A callback that returns true or false is called a predicate. Passing a predicate lets one function handle endless variations of a question:

function countUpTo(limit, check) {
  let count = 0;
  for (let n = 1; n <= limit; n++) {
    if (check(n)) count++;
  }
  return count;
}

const isEven = (n) => n % 2 === 0;
console.log(countUpTo(10, isEven));               // 5
console.log(countUpTo(10, (n) => n > 7));         // 3

Passing a function versus calling it

This is the classic mistake with callbacks:

function sayHi() {
  console.log("Hi!");
}

doTwice(sayHi);   // ✔ passes the function: doTwice calls it twice
doTwice(sayHi()); // ✘ calls sayHi right now and passes its result (undefined)
                  //   → TypeError: action is not a function

Without parentheses you hand over the function itself. With parentheses you call it immediately and hand over whatever it returned.

Built-in higher-order functions

JavaScript is full of them. setTimeout(callback, 1000) calls your callback after one second, and arrays have forEach, map, filter, reduce and more, all of which take callbacks. You'll use them throughout the rest of this course.

Common mistakes

  • Calling instead of passing: run(fn()) instead of run(fn).
  • Forgetting to return the callback's result. If your higher-order function should produce a value, return fn(value), don't just call it.
  • Ignoring the arguments. If a function calls your callback with (item, index), your callback can use both. Check what the caller passes.

Assignment

Write three higher-order functions:

  1. applyTwice(fn, value) calls fn on value, then calls fn again on the result, and returns the final result.
    • applyTwice((n) => n * 2, 3) → 12
    • applyTwice((s) => s + "!", "Hi") → "Hi!!"
  2. repeat(times, action) calls action exactly times times, passing the round number each time: action(0), action(1), …, action(times - 1). It doesn't need to return anything.
  3. countMatching(from, to, check) returns how many whole numbers from from to to (both included) make check(n) return true.
    • countMatching(1, 10, (n) => n % 2 === 0) → 5

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+20 XP

Lesson 12 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.