Functions as Values: Callbacks

Pass a function into another function and let it decide when to call it. Use a named function, then an arrow.

JavaScript · beginner · 6 min · 21 steps · free

What you'll learn

Callbacks.js

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

function shout(n) {
  console.log(`Hello #${n}!`);
}

repeat(2, shout);
repeat(2, (n) => console.log('arrow', n));

Step by step

  1. Before the first line runs, JavaScript reads the whole file: the functions repeat, shout already exist. This is called hoisting.
  2. action holds the function shout itself, not a result. Functions are values: they can be stored and passed around.
  3. i <= times is true, so the loop body runs.
  4. JavaScript calls shout(), with n = 1. It gets its own variables.
  5. It prints Hello #1!.
  6. action(i) calls whatever function was passed in. Here, shout.
  7. i <= times is true, so the loop body runs.
  8. JavaScript calls shout(), with n = 2. It gets its own variables.
  9. It prints Hello #2!.
  10. shout() has finished, so its variables are gone.
  11. i <= times is false, so the loop ends.
  12. repeat() has finished, so its variables are gone.
  13. This time an arrow function is passed straight in, without a name.
  14. i <= times is true, so the loop body runs.
  15. The arrow function gets n = 1 and returns undefined.
  16. (n) => console.log('arrow', n) has finished, so its variables are gone.
  17. i <= times is true, so the loop body runs.
  18. The arrow function gets n = 2 and returns undefined.
  19. (n) => console.log('arrow', n) has finished, so its variables are gone.
  20. i <= times is false, so the loop ends.
  21. repeat() has finished, so its variables are gone.

Common mistakes

Best practices

Key takeaways

Check yourself

arr.forEach(log): what is log?

Answer: A callback

repeat(1, () => 5) calls the arrow?

Answer: Yes, once

·

More in Functions