A callback function can be executed repeatedly by passing it to another function that controls the number of iterations. JavaScript provides loops, recursion, and array methods to achieve this.
- Use a for loop for the simplest and most efficient approach.
- Use recursion when the callback execution depends on a recursive condition.
- Array.from() with forEach() can be used for index-based iterations.
Approach 1: Using a for Loop
A for loop is the simplest way to execute a callback a specific number of times.
function iterateCallback(n, callback) {
if (n <= 0) {
console.log("Invalid number of iterations");
return;
}
for (let i = 1; i <= n; i++) {
callback(i);
}
}
function printIndex(index) {
console.log(`Iteration ${index}`);
}
iterateCallback(5, printIndex);
Output
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
Syntax:
for (let i = 1; i <= n; i++) {
callback(i);
}
Approach 2: Using Recursion
Recursion can repeatedly execute the callback until the specified number of iterations is reached.
function iterateCallback(n, callback, index = 1) {
if (index > n) {
return;
}
callback(index);
iterateCallback(n, callback, index + 1);
}
function printIndex(index) {
console.log(`Iteration ${index}`);
}
iterateCallback(5, printIndex);
Output
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
Approach 3: Using Array.from() and forEach()
Array.from() can create an array-like structure with n elements. The forEach() method can then execute the callback for each element.
function iterateCallback(n, callback) {
if (n <= 0) {
console.log("Invalid number of iterations");
return;
}
Array.from({ length: n }).forEach((_, index) => {
callback(index + 1);
});
}
function printIndex(index) {
console.log(`Iteration ${index}`);
}
iterateCallback(5, printIndex);
Output
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
Syntax:
Array.from({ length: n }).forEach((_, index) => callback(index + 1));Approach 4: Using Array.from()
The callback can also be executed directly while creating the array with Array.from().
function iterateCallback(n, callback) {
if (n <= 0) {
console.log("Invalid number of iterations");
return;
}
Array.from({ length: n }, (_, index) => callback(index + 1));
}
function printIndex(index) {
console.log(`Iteration ${index}`);
}
iterateCallback(5, printIndex);
Output
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
Note: For most cases, the for loop is the clearest choice when the goal is simply to execute a callback exactly n times.