How to iterate over a callback n times in JavaScript?
Last Updated :
01 Jul, 2024
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:
Using recursion to iterate the n times callback function.
- First, create a callback function factor that takes n as an argument.
- The factor function generates a pattern of n length.
- Create a test function that takes a callback function and n.
- The test function checks the value of n is equal to 0 and not.
- If n is 0 it returns the terminate test function, else it calls the callback function which prints the pattern.
Example: This example uses the above approach.
JavaScript
// 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 pattern
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);
Output01 02 03 04
01 02 03
01 02
01
Using a loop statement to iterate over the callback.
- 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.
JavaScript
// 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);
Outputfactorial of 5 is
120
factorial of 4 is
24
factorial of 3 is
6
factorial of 2 is
2
factorial of 1 is
1
Using Array.from() and Array.prototype.keys() for Index-Based Iteration
In this approach, we'll convert the number of iterations (n) into an array of n elements using Array.from() and then use Array.prototype.keys() to iterate over the indices of the array. This allows us to effectively control the number of iterations and use the index to invoke the callback function.
Example: This example demonstrates the usage of Array.from() and Array.prototype.keys() to iterate over a callback function multiple times.
JavaScript
// Callback function that prints the index
function printIndex(index) {
console.log(`Iteration ${index}`);
}
// Function to iterate over callback function
function iterateCallback(n, callback) {
if (n <= 0) {
console.log("Invalid number of iterations");
return;
}
// Create an array of size n, then iterate over its keys
Array.from({ length: n }, (_, index) => callback(index + 1));
}
let numIterations = 5;
iterateCallback(numIterations, printIndex);
OutputIteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Using forEach() Method
The forEach() method can be used to iterate over an array. By creating an array of a specified length using Array.from(), we can use forEach() to call the callback function n times.
Syntax
Array.from({ length: n }).forEach((_, index) => callback(index + 1));
Example: The example below demonstrates how to use the forEach() method to iterate over the callback function n times.
JavaScript
// Callback function that prints the index
function printIndex(index) {
console.log(`Iteration ${index}`);
}
// Function to iterate over callback function
function iterateCallback(n, callback) {
if (n <= 0) {
console.log("Invalid number of iterations");
return;
}
// Create an array of size n, then iterate over its elements
Array.from({ length: n }).forEach((_, index) => callback(index + 1));
}
let numIterations = 5;
iterateCallback(numIterations, printIndex);
OutputIteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Similar Reads
How to call JavaScript function in HTML ? In HTML, you can easily call JavaScript functions using event attributes like onclick and onload. Just reference the function name within these attributes to trigger it. You can also call functions directly within script blocks using standard JavaScript syntax. Let's create an HTML structure with so
2 min read
setTimeout() in JavaScript The setTimeout() function is used to add delay or scheduling the execution of a specific function after a certain period. It's a key feature of both browser environments and Node.js, enabling asynchronous behavior in code execution.JavaScriptsetTimeout(function() { console.log('Hello, world!'); }, 2
2 min read
What is a typical use case for anonymous functions in JavaScript ? In this article, we will try to understand what exactly an Anonymous function is, and how we could declare it using the syntax provided in JavaScript further we will see some examples (use-cases) where we can use anonymous functions to get our results in the console. Before proceeding with the examp
4 min read
How to check whether a number is NaN or finite in JavaScript ? When working with numbers in JavaScript, it's important to know how to determine if a value is NaN (Not-a-Number) or finite. This knowledge is crucial for data validation, error handling, and ensuring your code behaves as expected. In this article, we will see how to check whether the number is NaN
3 min read
How to Encode and Decode a URL in JavaScript? Encoding and decoding URLs in JavaScript is essential for web development, especially when making GET requests with query parameters. This process ensures special characters in URLs are correctly interpreted by the server. For instance, spaces are converted to %20 or + in URLs. This guide covers how
4 min read
How to declare the optional function parameters in JavaScript ? Declaring optional function parameters in JavaScript means defining function parameters that aren't required when the function is called. You can assign default values to these parameters using the = syntax, so if no argument is provided, the default value is used instead. These are the following ap
3 min read
How to get the javascript function parameter names/values dynamically ? In this article, we are given any arbitrary JavaScript function and the task is to return the parameter names of the function. Approach: JavaScript contains a method called toString() which is used to represent a function code in its string representation. This method is used to get the parameter na
2 min read
How To Include a JavaScript File in Another JavaScript File? The import and export syntax available in ES6 (ECMAScript 2015) module is used to include a JavaScript file in another JavaScript file. This approach is the most modern and recommended way to share code between JavaScript files.It allows you to break your code into smaller modules and then import th
4 min read
How to override a JavaScript function ? In this article, we are given an HTML document and the task is to override the function, either a predefined function or a user-defined function using JavaScript. Approach: When we run the script then Fun() function is called. After clicking the button the GFG_Fun() function is called and this funct
2 min read
Using the function* Declaration in JavaScript The function* declaration is used to define a generator that returns a Generator object. Generators are very powerful for asynchronous programming as they aim to resolve callback problems. In a generator, the yield keyword is used instead of return. The yield statement suspends the functionâs execut
2 min read