Lodash toLength Maximum Value Explained
The Lodash library provides the _.toLength utility
function to safely convert any JavaScript value into a valid integer
suitable for use as the length of an array-like object. This article
explains the exact maximum limit enforced by _.toLength,
the technical reasons rooted in the ECMAScript specification for this
ceiling, and how the function handles numbers that exceed it.
The maximum value enforced by _.toLength in Lodash is
4294967295 (\(2^{32} -
1\)).
Why 4294967295?
In standard JavaScript (ECMAScript), an array length is defined as an
unsigned 32-bit integer. The maximum index an array can have is \(2^{32} - 2\) (4,294,967,294), which gives
standard JavaScript arrays a maximum capacity of \(2^{32} - 1\) elements. Lodash aligns with
this native specification by declaring an internal constant,
MAX_ARRAY_LENGTH, set to 4294967295.
How _.toLength
Handles Values
When converting inputs, _.toLength follows strict
boundary rules:
- Values greater than 4294967295: Any integer,
floating-point number, or infinity that surpasses
4294967295is capped and returned as4294967295. - Values less than 0: Any negative number or value
evaluating to less than zero is clamped to
0. - Falsy or non-numeric values: Inputs such as
null,undefined,NaN, or empty strings default to0. - Valid ranges: Values between
0and4294967295are converted to their integer floor representation.
Example Outputs
_.toLength(Infinity);
// => 4294967295
_.toLength(5000000000);
// => 4294967295
_.toLength('3.2');
// => 3
_.toLength(-10);
// => 0By clamping values between 0 and
4294967295, _.toLength guarantees that the
returned integer will never trigger a
RangeError: Invalid array length when creating or sizing
array structures in JavaScript.