JavaScript Number.isSafeInteger(value) function


The Number.isSafeInteger(value) function in JavaScript is a static method that determines whether the provided value is a safe integer. A safe integer is defined as an integer that can be exactly represented as an IEEE-754 double-precision number, and it lies within the range of −253+1-2^{53} + 1 to 253−12^{53} - 1 (inclusive). This range is necessary because JavaScript uses double-precision floating-point format for all numbers.

Syntax:

Number.isSafeInteger(value)
  • value: The value to be tested.

Return Value:

  • Returns true if the value is a safe integer; otherwise, it returns false.

Key Characteristics:

  1. Safe Integer Definition: Safe integers are integers within the range of −253+1-2^{53} + 1 to 253−12^{53} - 1, which is equivalent to −9007199254740991-9007199254740991 to 90071992547409919007199254740991. Any integer outside this range may not be represented accurately due to the limitations of the floating-point format.

  2. Integer Check: The function first checks whether the value is an integer using the Number.isInteger() method before checking if it lies within the safe integer range.

Example 1: Safe Integers

console.log(Number.isSafeInteger(10)); // true console.log(Number.isSafeInteger(-9007199254740991)); // true console.log(Number.isSafeInteger(9007199254740991)); // true

In these examples, all values are within the safe integer range, so the function returns true.

Example 2: Unsafe Integers

console.log(Number.isSafeInteger(9007199254740992)); // false console.log(Number.isSafeInteger(-9007199254740992)); // false console.log(Number.isSafeInteger(3.14)); // false

In these cases, the values 9007199254740992 and -9007199254740992 are outside the safe integer range, and 3.14 is not an integer, resulting in false.

Example 3: Non-integer Values

console.log(Number.isSafeInteger("123")); // false console.log(Number.isSafeInteger(null)); // false console.log(Number.isSafeInteger(NaN)); // false

Here, non-integer values such as strings, null, and NaN are not considered safe integers, so the function returns false.

Example 4: Special Cases

  • Infinity and -Infinity: These values are also not considered safe integers.
console.log(Number.isSafeInteger(Infinity)); // false console.log(Number.isSafeInteger(-Infinity)); // false

Summary:

  • The Number.isSafeInteger(value) function checks if a value is a safe integer, meaning it must be an integer within the range of −253+1-2^{53} + 1 to 253−12^{53} - 1.
  • It returns true for safe integers and false for integers outside this range, as well as for non-integer and non-numeric values.
  • This method is particularly useful when dealing with integer calculations where precision is critical, as it helps to avoid issues that can arise from using large integers in JavaScript.