In this lesson, you gave Tomás a countdown for the start of the film, and let the caller decide what happens at each count by handing it a function.
Key Points
- A function is a value, so you can pass it to another function as an argument, like a number or a string.
- The function that receives it decides when to call it and with which arguments. In
countdown(), the loop callsannouncewith each count, so you never callsayCountyourself. Each count arrives as the callback’s argument, whatever the callback names its parameter. InsayCount, that parameter isnumber. - A function you hand to another function, for it to call later, is a callback.
- You can pass a named function, such as
sayCount, or write an arrow right in the call. The arrow’s(count)is its parameter list, and its body runs only whencountdown()calls it. - With no parentheses after the function’s name, you hand over the function. With parentheses after it, you call it now and hand over whatever it returns.
Watch the Parentheses
Passing sayCount() instead of sayCount runs sayCount() right away, with no argument, so its parameter number is undefined. It logs undefined... and, with no return statement, gives back undefined. That undefined lands in announce, so the loop fails when it tries to call it:
countdown(3, sayCount());
Running the script prints one line, then stops with an error. Here’s the output, with the file path and most of the stack trace shortened:
undefined...
.../countdown.js:3
announce(count);
^
TypeError: announce is not a function
at countdown (.../countdown.js:3:5)
...
The error points inside countdown(), but the mistake is in the call.
Final Code
countdown.js
function countdown(n, announce) {
for (let count = n; count > 0; count--) {
announce(count);
}
}
function sayCount(number) {
console.log(`${number}...`);
}
countdown(3, sayCount);
countdown(3, (count) => console.log(`Coco starts in ${count}`));
Run it from your terminal, and each call counts down from three:
$ node countdown.js
3...
2...
1...
Coco starts in 3
Coco starts in 2
Coco starts in 1
The loop in countdown() is the same for both calls. Only the callback you hand it changes what each count prints.
Next, in Give Parameters Default Values, you’ll give a parameter a value to use when the call leaves it out.