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:

  1. It must be a primitive number: The value's type must evaluate to number. Values such as numeric strings ("5"), objects, null, or undefined will return false.
  2. 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.
  3. 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.
  4. It must not exceed the maximum safe integer: The value cannot exceed Number.MAX_SAFE_INTEGER (\(2^{53} - 1\), or 9007199254740991). 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:

Examples of Invalid Lengths

The following values violate one or more of the rules and return false: