How to Loop Number of Times in JavaScript

How to Loop Number of Times in JavaScript

Ferenc Almasi β€’ Last updated 2024 February 02 β€’ Read time 3 min read
  • twitter
  • facebook
JavaScript

The general way to loop x number of times in JavaScript is using a simple for loop, where you can define how many times you want to loop over something:

Copied to clipboard! Playground
const loopTime = 5

for (let i = 0; i < loopTime; i++) {
    console.log(`Iteration is #${i}`)
}
Loop number of times in JavaScript
  • let i = 0: The first statement is executed before the loop just once. This is where we define a counter, usually named by i. Here we say that i should be equal to 0.
  • i < loopTime: The second defines the condition for how long the loop should run. Here we can set the number of loops. In the above example, it means the code should be executed as long as i is less than loopTime. Essentially, this means that we want the code to be executed 5 times.
  • i++: The third is executed every time after the block of code inside the curly braces has been executed. It means that we want to increment i by one. It's the same as saying i = i + 1. This way, the condition will be met in the second statement after i becomes 5.

Loop Number of Times Using Functions

Using a for loop works just fine and is the most performant and simplest solution of all, but we can make things a bit more readable using functions. To loop a number of times using a function, we can introduce a loop function that executes a for loop internally:

Copied to clipboard! Playground
const loop = (times, callback) => {
    for (let i = 0; i < times; i++) {
        callback(i)
    }
}
The iteration in this case will start at 0.

Using the above function, we can loop over things over a predefined number of times. Note that we have passed the i variable to the callback function, so that whenever we call the loop function, we'll have access to the current loop's iteration. We can use the loop function in the following way:

Copied to clipboard!
loop(5, i => {
    console.log(`Iteration is #${i}`)
})
Loop 5 times and log the current iteration to the console

Improving Loop Readability

We can further make things more readable, by using a helper array instead of the for loop:

Copied to clipboard!
const loop = (times, callback) => {
    Array(times).fill(0).forEach((item, i) => callback(i))
};
Improving loop readability with array methods

This will work just like using the for loop. If you call the loop function with a value of 5, it'll create an array of 5 with zeroes inside it, so we actually have something to loop over.

Note that in terms of performance, using for loops will win over using array methods.

Using the spread operator

We can further shorten this code by using the spread operator and omitting the fill method:

Copied to clipboard!
const loop = (times, callback) => {
    [...Array(times)].forEach((item, i) => callback(i));
};
Shortening function with the spread operator

The reason we don't need to use fill this time is because we get an array with the values of undefined, instead of empty x 5, meaning we'll have the correct length without having to use fill. Changing callback(i) to callback(i + 1), we can start the counter from 1 instead of 0 if necessary. You can try out the function with the editor below:

🚫 Refresh console
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Resources

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.