How Lodash _.times Works with an Iteratee

In the Lodash JavaScript library, passing an iteratee to the _.times function allows you to execute a specific callback function a designated number of times and automatically collect its return values into a new array. This article explains the exact behavior of _.times, what arguments are supplied to the iteratee during execution, and how the output is structured.

How the Iteratee Is Executed

The _.times method accepts two primary arguments: n (the number of iterations) and iteratee (the function to invoke). When an iteratee function is passed, Lodash executes it sequentially n times, beginning from index 0 up to n - 1.

On each execution, _.times passes a single argument to the iteratee: the current iteration index. For instance, if n is set to 4, the iteratee will be invoked four times with the arguments 0, 1, 2, and 3, respectively.

const _ = require('lodash');

const results = _.times(3, (index) => {
  return `Item ${index}`;
});

console.log(results);
// Output: ['Item 0', 'Item 1', 'Item 2']

Collecting Return Values

Unlike basic looping constructs such as while or for loops, _.times functions as a generator and mapper. Whatever value your iteratee returns during an iteration is captured and placed at the corresponding index of the returned array.

If the iteratee does not explicitly return a value, the resulting array will contain undefined for that iteration:

const sideEffectsOnly = _.times(3, (index) => {
  console.log(`Running iteration ${index}`);
});

console.log(sideEffectsOnly);
// Output: [undefined, undefined, undefined]

Contrast with the Default Iteratee

If you omit the iteratee argument, Lodash defaults to _.identity, which simply returns the argument it receives (the index). Consequently, calling _.times(4) returns [0, 1, 2, 3]. By providing a custom iteratee, you override this behavior, allowing for dynamic object creation, mathematical transformations, or repeated function calls mapped directly into an array.

Handling Edge Cases

If the count n provided to _.times is 0, a negative number, or not a safe integer, the iteratee will not be invoked at all, and the method will immediately return an empty array [].