Callbacks
Functions as values.
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.

- 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.
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));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.
| key | value |
|---|---|
| Callback | a function passed in |
| cheer | pass the function |
| cheer() | calls it now |
| Used by | arrays, 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