AI Hints
Home›JavaScript Tutorial›Callbacks and Recursion
JavaScript · Lesson 37 of 138

Callbacks

Functions as values.

⏱ 2 min read▶ Video at 44:38🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

In JavaScript, functions are values, just like numbers and strings. You can store them in variables, and pass them to other functions. A function you pass to another function is called a callback.

Callbacks
From the video: Callbacks
  • Functions are values
  • Store them, pass them
  • Callbacks

Passing a function

Repeat takes a number, and a function. It calls that function the given number of times, passing in the round number. We can pass a named function, or write an arrow function right there in the call. Run it.

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

function cheer(n) {
  console.log(`Hip hip hooray number ${n}!`);
}

repeat(2, cheer);
repeat(3, (n) => console.log("Step", n));
Output
Hip hip hooray number 1!
Hip hip hooray number 2!
Step 1
Step 2
Step 3

Callbacks are everywhere

You'll use callbacks constantly. Array methods like map and filter take callbacks. Web pages call your callback when a button is clicked. Timers call your callback after a delay. When you pass a callback, don't add brackets. Cheer passes the function. Cheer with brackets would call it straight away.

keyvalue
Callbacka function passed in
cheerpass the function
cheer()calls it now
Used byarrays, events, timers

Summary

Functions are values, and a callback is a function passed to another function, to be called later. Next, a practice project.

Key takeaways
  • Pass functions as values
  • Arrow callbacks inline
  • No brackets when passing
Next up: Practice: A Tip Calculator — functions together