Call function 'n' times in JavaScript

Sometimes you need to call a function a given number of times. There is no purpose-built function to do exactly this, but it can easily be done with Array:

// Log "hi" five times 
Array.from({length: 5}, () => console.log('hi'));

// Get two random dates
const randomDate = () => new Date(new Date() - Math.random()*(1e+12));
const dates = Array.from({length: 2}, randomDate);

// Create string "1,2,3,,,100"
Array.from({length: 100}, (_, i) => i+1).join();

That's short and simple enough to be used just like that - really, use it - but if your project needs this often, a utility function like this might be worth it:

/**
 * Call a function _n_ times.
 * @param {function(number?)} callback - The function to call.
 * @param {number} times - The number of times `callback` will be called.
 * @param {boolean} withIndex - Pass the current index as an arg to `callback`.
 * @param {...*} args - The rest of the arguments (optional).
 * @return {*[]}
 */
function repeat(callback, times = 1, withIndex = false, ...args) {
  return Array.from({length: times}, (_, i) => {
    withIndex ? callback(...args, i) : callback(...args);
  });
}

Let's compare:

// Log "hi" five times 
repeat(console.log, 5, 'hi');
Array.from({length: 5}, () => console.log('hi'));

// Get two random dates
const randomDate = () => new Date(new Date() - Math.random()*(1e+12));
const dates = repeat(randomDate, 2);
const dates = Array.from({length: 2}, randomDate);

// Create string "1,2,3,,,100"
repeat(i => i+1, 100, true).join();
Array.from({length: 100}, (_, i) => i+1).join();

Using Array is always going to be short and simple and flexible, but a frequent need to do this would benefit from a utility function.

Be cautious to avoid unnecessary use of this approach when iterating an actual list. For example, if you want to do something once for every item in the list there is likely a built-in Array method better suited for the job even when you aren't referencing those items:

// Don't
const options = Array
  .from(list, (_, i) => `<option value="${i}">${i+1}</option>`)
  .join();

// Do
const options = list.reduce((acc, _, i) => `${acc}<option value="${i}">${i+1}</option>`, '');