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
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));repeat, shout already exist. This is called hoisting.action holds the function shout itself, not a result. Functions are values: they can be stored and passed around.i <= times is true, so the loop body runs.shout(), with n = 1. It gets its own variables.Hello #1!.action(i) calls whatever function was passed in. Here, shout.i <= times is true, so the loop body runs.shout(), with n = 2. It gets its own variables.Hello #2!.shout() has finished, so its variables are gone.i <= times is false, so the loop ends.repeat() has finished, so its variables are gone.i <= times is true, so the loop body runs.n = 1 and returns undefined.(n) => console.log('arrow', n) has finished, so its variables are gone.i <= times is true, so the loop body runs.n = 2 and returns undefined.(n) => console.log('arrow', n) has finished, so its variables are gone.i <= times is false, so the loop ends.repeat() has finished, so its variables are gone.Answer: A callback
Answer: Yes, once
← Recursion · Arrays and References →