What Is a Valid Length in Lodash isLength
In the Lodash JavaScript library, the _.isLength method
checks whether a given value is suitable to be used as the length of an
array-like object. This article breaks down the exact technical criteria
that Lodash uses to determine a valid length, explains the underlying
rules according to its source implementation, and provides examples of
values that pass and fail this validation.
According to Lodash, a value constitutes a valid length if and only if it meets four specific conditions simultaneously:
- It must be a primitive number: The value's type
must evaluate to
number. Values such as numeric strings ("5"), objects,null, orundefinedwill returnfalse. - It must be greater than or equal to zero: Negative
numbers cannot represent lengths. In the Lodash source code, this is
validated using
value > -1. - It must be an integer: Fractional or floating-point
numbers are not valid lengths. Lodash validates this condition using the
modulo operation
value % 1 == 0. - It must not exceed the maximum safe integer: The
value cannot exceed
Number.MAX_SAFE_INTEGER(\(2^{53} - 1\), or9007199254740991). Numbers beyond this limit lose precision in JavaScript and are considered unsafe for indexing or measuring collections.
In the official Lodash source code, this logic is implemented concisely as:
const MAX_SAFE_INTEGER = 9007199254740991;
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}Examples of Valid Lengths
The following values satisfy all criteria and return
true:
0(represents an empty collection)3(standard positive integer)9007199254740991(Number.MAX_SAFE_INTEGER)
Examples of Invalid Lengths
The following values violate one or more of the rules and return
false:
Infinity(exceedsMAX_SAFE_INTEGER)-1(fails the non-negative check)1.5(fails the integer check)"3"(fails thenumbertype check)NaN(fails the comparison and integer checks)Number.MAX_SAFE_INTEGER + 1(exceeds the maximum safe integer limit)