How to use a loop statement to iterate over the callback. In Javascript
- First, we create a callback function factor which generates a factorial of numbers.
- Create a test function with argument n and a callback function.
- Check the value of n if it is invalid terminate if not continue.
- Create for loop with range n.
- On each loop call the callback function which prints the factorial of each number.
Example: This example describes the above explained approach.
<script>
// call back function that 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("invalid 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
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. To iterate over the callback function, we have to run the callback function n time.
Here we have some common approaches:
Table of Content
- Using recursion
- Using a loop statement
- Using Array.from() and Array.prototype.keys()