What is isSafeInteger() in Javascript?
isSafeInteger() is a Number method that is used to determine if a given value is a safe integer. A safe integer is an integer that is in the range -( - 1) to ( - 1).
Declaration
The isSafeInteger() method is declared as follows:
Number.isSafeInteger(value)
value: The value to be tested to check whether it is a safe integer or not.
Return value
The isSafeInteger() method returns a boolean depending on the value as follows:
- The
isSafeInteger()method returnsfalseifvalueis not a safe integer. - The
isSafeInteger()method returnstrueifvalueis a safe integer.
Browser compatibility
The isSafeInteger() method is supported by the following browsers:
- Edge 12
- Firefox 32
- Google Chrome 19
- Opera 22
- Safari 9
Examples
Example 1
Consider the code snippet below, which demonstrates the use of the isSafeInteger() method:
var foo = Number.isSafeInteger( -(Math.pow(2, 53)-1) ) // -2^53 - 1console.log("Given value is integer: ",foo);var foo = Number.isSafeInteger(0)console.log("Given value is integer: ",foo);var foo = Number.isSafeInteger(Math.pow(2, 53)-1) // 2^53 - 1console.log("Given value is integer: ",foo);
Explanation
Positive, negative, and 0 integers are passed to the isSafeInteger() method in line 1, line 4, and line 7, respectively. The isSafeInteger() method returns true, as the given values are integers in the range -( - 1) to ( - 1).
Example 2
Consider the code snippet below, in which non-integers and non-safe integers are passed to the isSafeInteger() method:
var foo = Number.isSafeInteger("123")console.log("Given value is integer: ",foo);var foo = Number.isSafeInteger(11.7)console.log("Given value is integer: ",foo);var foo = Number.isSafeInteger(Infinity)console.log("Given value is integer: ",foo);var foo = Number.isSafeInteger(NaN)console.log("Given value is integer: ",foo);var foo = Number.isSafeInteger(true)console.log("Given value is integer: ",foo);var foo = Number.isSafeInteger(Math.PI)console.log("Given value is integer: ",foo);var foo = Number.isSafeInteger([1])console.log("Given value is integer: ",foo);var foo = Number.isSafeInteger(Math.pow(2, 53)+1) // 2^53 + 1console.log("Given value is integer: ",foo);
Explanation
Non-integers and non-safe integers are passed to the isSafeInteger() method in the code snippet above. The isSafeInteger() method returns false for the non-integers and non-safe integers.
Free Resources