Lodash _.times with Fractional Numbers
When using the _.times method in the Lodash JavaScript
library with a fractional number, Lodash internally converts the
argument into an integer before executing the loop. Specifically, it
applies an internal conversion equivalent to Math.trunc(),
which drops the decimal portion and iterates only the whole number of
times. This article explains the technical mechanics, the resulting
execution consequences, and how edge cases behave when passing
non-integer floats to _.times.
Internal Type Coercion:
toInteger
Under the hood, Lodash processes the count argument n
using its internal toInteger helper function. This function
converts the input to a finite number and removes the fractional
remainder, truncating toward zero.
Because of this coercion, _.times does not throw an
error, crash, or attempt partial execution when given a float. Instead,
it silently rounds down toward zero for positive numbers and rounds up
toward zero for negative numbers.
Execution Behavior with Examples
Positive Fractional Numbers
When passed a positive floating-point number, _.times
strips the decimal portion and runs the iteratee function according to
the remaining integer:
_.times(3.8, (index) => index);
// Returns: [0, 1, 2]In this case, 3.8 becomes 3. The iteratee
function executes exactly three times, yielding an array of three
items.
Fractions Between 0 and 1
If the number provided is greater than 0 but less than
1, truncating the fractional part yields
0:
_.times(0.75, (index) => index);
// Returns: []Because n becomes 0, the condition
n < 1 triggers immediately, returning an empty array
without ever invoking the iteratee.
Negative Fractional Numbers
Any negative value passed to _.times results in an
integer less than or equal to 0:
_.times(-2.5, (index) => index);
// Returns: []Lodash checks if the integer value is less than 1. Since
-2 is less than 1, execution stops and an
empty array is returned.
Key Consequences for Developers
- Silent Truncation: Lodash does not round to the
nearest integer (
Math.round); it always truncates toward zero (Math.trunc). Passing4.99executes only 4 times, not 5. - No Runtime Exceptions: Passing a float will not
trigger a
TypeErroror runtime crash, which can mask unintentional floating-point calculations upstream in your application logic. - Array Pre-allocation: Lodash uses the truncated
value to pre-allocate array memory up to
MAX_ARRAY_LENGTH. Since the value is properly sanitized into an integer, array allocation remains safe from fractional sizing issues.
To prevent unexpected behavior, sanitize your inputs explicitly using
Math.floor(), Math.ceil(), or
Math.round() prior to calling _.times so that
your code's rounding intent is clear and predictable.