CuteMachine

How To Do Something N Times In JavaScript

Back when I was still programming in Ruby, I used the following code snippet quite often.

10.times do |i|
  do_something(i)
end

The statement would execute do_something() ten times.

What is the equivalent in JavaScript?

Indeed, there is a solution, although it is not as elegant as the Ruby code above.

You can run all examples in this article with the excellent RunJS REPL.1

Using Array.forEach() To Repeat Something Several Times

An easy solution is to call forEach() on an array.

[1, 2, 3].forEach(() => console.log('do something'))

Although this solution works, it might be a little too much typing when you need to repeat your loop a million times; Array.from to the rescue.

Using Array.from() To Repeat Something N Times

With Array.from() we can create an array from an array-like object. In the below example, the array-like object is { length: 3 }. Therefore the call will create an array with three elements. The function passed as the second argument to Array.from() will be called three times.

const n = Array.from({ length: 3 }, (x, i) => console.log(`done ${i}`))
// 'done 0'
// 'done 1'
// 'done 2'
n    //  [ undefined, undefined, undefined ]

We are not using the returned array; we are only using the fact that the passed function will be executed. If we wanted to use the created array n we could have used the i parameter to fill the array.

const n = Array.from({ length: 3 }, (x, i) => i )
n    // [ 0, 1, 2 ]

Using Lodash To Repeat Something X Times

Lodash offers an appropriate solution through its times() function.

import times from 'lodash/times'
const n = times(3, () => console.log('do something'))
// 'do something'
// 'do something'
// 'do something'
const m = times(3, (i) => i)
m    // [ 0, 1, 2 ]

As usual, Lodash offers a solution that is elegant and at the same time readable.

Using Array.fill() annd Array.map() To Repeat Something In JS

const n = Array(3).fill().map(() => console.log('do something'))
// 'do something'
// 'do something'
// 'do something'

Conclusion

Well, these are all solutions that come up when we are trying to be clever. But while we do, we should not forget the most straightforward solution. Just using a simple loop like this:

let n = 3
while(n--) {
  console.log('do something')
}
// 'do something'
// 'do something'
// 'do something'

  1. Run Eval Print Loop

Posted on CuteMachine.

Jo's Profile ImageWritten by Jo who lives and works in Frankfurt building digital doodah. Stalk him on Twitter.

TOS • Privacy • Disclaimer