Lodash isSafeInteger Numerical Boundaries
The Lodash _.isSafeInteger method verifies whether a
provided value is an integer that falls within the safe range for
JavaScript numeric operations. This article covers the exact minimum and
maximum numerical boundaries enforced by _.isSafeInteger,
why these limits exist under the IEEE-754 standard, and how the method
helps prevent precision loss in modern applications.
The Numerical Boundaries
The _.isSafeInteger function checks whether a value is
an integer between:
- Minimum boundary:
-(2^53 - 1)or-9007199254740991(Number.MIN_SAFE_INTEGER) - Maximum boundary:
2^53 - 1or9007199254740991(Number.MAX_SAFE_INTEGER)
The check is inclusive, meaning both -9007199254740991
and 9007199254740991 return true. Any integer
less than -9007199254740991 or greater than
9007199254740991 returns false.
Why These Boundaries Exist
JavaScript stores all standard numbers as 64-bit floating-point values according to the IEEE-754 specification. In this format:
- 1 bit is used for the sign.
- 11 bits are used for the exponent.
- 52 bits are used for the fraction (mantissa).
Because the mantissa includes an implicit leading bit, JavaScript can
represent integers with exact precision up to 53 bits. Beyond
2^53 - 1, the spacing between representable integers
becomes greater than 1. This causes rounding errors, where different
mathematical integers are mapped to the same floating-point value.
How Lodash Validates Safe Integers
For _.isSafeInteger(value) to return true,
the argument must satisfy three strict requirements:
- It must be an integer (not a fraction or decimal).
- It must be a primitive number or a
Numberobject (not a string, boolean, or other data type). - It must fall within the range
[-9007199254740991, 9007199254740991].
This behavior directly mirrors the standard ECMAScript method
Number.isSafeInteger(), providing safety and predictability
when working with large database IDs, timestamps, or 64-bit data.