JavaScript Number.isSafeInteger() Method

Shubham Vora Sep 19, 2022
  1. Syntax
  2. Parameters
  3. Returns
  4. Example Codes
JavaScript Number.isSafeInteger() Method

In JavaScript, we use the Number.isSafeInteger() method to check if the value of a variable is the safe integer or not.

The safe integer means that all numbers we can represent as an IEEE-754 double precision number. The range of the safe integer values in JavaScript is between -(2^53) + 1 to (2^53)-1.

Syntax

let integer = 123;
Number.isSafeInteger(integer);

Parameters

value This is the value required and passed to the Number.isSafeInteger() method to check whether it is a safe integer.

Returns

The Number.isSafeInteger() always returns false for non-numeric values and true for all numeric safe integer values.

Example Codes

Let’s use various numeric and non-numeric values to learn the working of Number.isSafeInteger() in JavaScript.

Use Number.isSafeInteger() With Various Numeric Values

In the following code, we have used the three different numeric values with the Number.isSafeInteger() method.

We can see in the output that for the -Infinity value, the method returns false as it is not in the range of -(2^53) + 1 to (2^53)-1, and for other numeric values, it returns true.

let value1 = 50;
let value2 = -(Math.pow(2,53))+1;
let value3 = -Infinity;

console.log(Number.isSafeInteger(value1));
console.log(Number.isSafeInteger(value2));
console.log(Number.isSafeInteger(value3));

Output:

true
true
false

Use Number.isSafeInteger() With Non-Numeric Values

When we pass the non-numeric values as an argument of the Number.isSafeInteger() method, it always returns false as it also checks the type of the values.

In this example, we have taken different values and objects to test its output with the Number.isSafeInteger() method.

let string = "DelftStack";
let object = {};

console.log(Number.isSafeInteger(string));
console.log(Number.isSafeInteger(object));

Output:

false
false

The Number.isSafeInteger() method is always helpful to check whether the value is a safe integer or not, and it fits between the IEEE-754 representation.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript Number