How to iterate over a callback n times in JavaScript ?
Given a callback function we have to iterate over a callback n times. The callback is a function that is passed as an argument. for iterate over callback function, we have to run callback function n time.
Approach 1: We use recursion to iterate n times callback function.
Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!
- First create callback function factor which takes n as argument.
- Factor function generate pattern of n length.
- Create test function that takes callback function and n.
- Test function checks value of n is equal to 0 and not.
- If n is 0 it return terminate test function, else it call callback function which print the pattern.
Example:
Javascript
<script> // callback function that print pattern function factor(n) { // base case for recursion if (n <= 1) { console.log("0" + n); return; } // string to store patterns let str = ""; // loop for generate patter for (let i = 1; i <= n; i++) { str += `0${i} `; } // printing patterns console.log(str); // recursion call with decrement by 1 return factor(n - 1); } // function to run callback function function test(n, callback) { if (n == 0) { console.log("please provide value n greater than 0"); return; } let k = n; //calling callback function callback(k); } // initialising test number let t_number = 4; // calling main function to call callback function test(t_number, factor);</script> |
Output:
01 02 03 04 01 02 03 01 02 01
Approach 2: We use loop statement to iterate over callback.
- First we create callback function factor which generate factorial of number.
- Create test function with argument n and callback function.
- Check value of n if it in invalid terminate if not continue.
- Create for loop with range n.
- On each loop call callback function which print factorial of each number.
Example:
Javascript
<script> // call back function thar return factorial function factor(number) { let j = 1; // loop that generate factorial of number for (let i = 1; i <= number; i++) { j *= i; } // printing value of factorial console.log(`factorial of ${number} is `); console.log(j); } // function that iterate over callback function function test(n, callback) { if (n <= 0) { console.log("invalide number"); return; } let k = n; // iterating over callback function with for loop for (let i = k; i >= 1; i--) callback(i); } // initialising test variable let t_umber = 5; // main function calling test(t_umber, factor);</script> |
Output:
factorial of 5 is 120 factorial of 4 is 24 factorial of 3 is 6 factorial of 2 is 2 factorial of 1 is 1

