Sikau

JavaScript · Day 27 · about 25 min

Functions as values

Handing a function to another function.

Passing the recipe along

You can hand a friend a recipe card and say "make this twice". In JavaScript, functions are values too — you can store them, and pass them to other functions. This idea powers clicks, timers and list tools you'll meet soon.

A function that takes a function

function twice(action) {
  action();
  action();
}

const wave = () => console.log("👋");
twice(wave);

A function you pass in to be called later is called a callback.

function repeat(times, action) {
  for (let i = 1; i <= times; i++) {
    action(i);
  }
}

repeat(3, (n) => console.log("Round " + n));

The rest of this lesson

  • Callbacks are everywhereexplain
  • Predict the outputpredict
  • Who calls it?predict
  • Your turnwrite code
  • Challengechallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript