Lodash toSafeInteger Handling Infinity
In the Lodash JavaScript library, passing Infinity to
the _.toSafeInteger function causes it to return
9007199254740991, which corresponds to
Number.MAX_SAFE_INTEGER. Conversely, passing
-Infinity returns -9007199254740991
(Number.MIN_SAFE_INTEGER). Rather than returning an error,
NaN, or preserving the infinite state, Lodash clamps the
value directly to the boundaries of safe integer representation in
JavaScript.
The Mechanism Behind Lodash's Clamping
JavaScript numbers are represented using the IEEE 754
double-precision floating-point format. Under this specification,
integers can only be accurately represented and safely compared without
loss of precision up to \(2^{53} - 1\).
This constant is exposed globally in modern runtimes as
Number.MAX_SAFE_INTEGER
(9007199254740991).
When _.toSafeInteger evaluates an argument, it undergoes
a two-step normalization process:
- Conversion to an Integer: The input is first
converted to an integer via Lodash's internal
toIntegerutility, handling edge cases, strings, and symbols. - Safe Clamping: Lodash checks whether the resulting
integer falls outside the range of \([-9007199254740991, 9007199254740991]\). If
the number exceeds the upper limit, it is clamped to
9007199254740991. If it falls below the lower limit, it is clamped to-9007199254740991.
Code Example
const _ = require('lodash');
console.log(_.toSafeInteger(Infinity));
// Output: 9007199254740991
console.log(_.toSafeInteger(-Infinity));
// Output: -9007199254740991
console.log(_.toSafeInteger(Infinity) === Number.MAX_SAFE_INTEGER);
// Output: trueWhy Lodash Clamps Infinity
The explicit contract of _.toSafeInteger is to guarantee
that the output can be treated as a safe integer in subsequent numeric
operations. Because Infinity is fundamentally an unbounded
floating-point value, allowing it to persist—or returning a value beyond
the safe integer threshold—would introduce arithmetic precision bugs. By
capping Infinity at Number.MAX_SAFE_INTEGER,
Lodash ensures that downstream calculations remain mathematically sound
within JavaScript's safe integer constraints.