Number.isInteger() is a new method of the Number object introduced as a part of ES6. This is an interesting and useful feature that can help you save some time with mathematical operations. The
Number.isInteger() method basically tells you if the number passed on to the method as a parameter or argument is an Integer or not. So say if I pass a number that is Integer to the method it would return a boolean true. However, if I pass anything else to it, it would return false. Let’s take a look at an example:
Number.isInteger(10); //returns true Number.isInteger(13.5); //returns false
Please note that the
Number.isInteger() method returns a Boolean value always.
Number.isInteger() should not be confused with the
parseInt() method. The
Number.isInteger() on the other hand checks if the parameter number passed to it is an integer already and returns true or false accordingly.
Number.isSafeInteger() on the other hand, is a method that is very similar to the
Number.isInteger(), however, it checks if the value is a “Safe Integer”, Safe integers are all integers from -(253 – 1) to +(253 – 1) i.e -9007199254740991 to 9007199254740991. Let’s take a look at an example:
Number.isSafeInteger(10); // returns true Number.isSafeInteger(12345678901234567890); // returns false Number.isSafeInteger(9007199254740991); // returns true Number.isSafeInteger(9007199254740992); // returns false
Please note that
Number.isSafeInteger() too returns a Boolean value (true or false) always.
You can find out the range of Safe Integer using two new properties of the number object which are
Number.MIN_SAFE_INTEGER (returns -9007199254740991) and
Number.MAX_SAFE_INTEGER (returns 9007199254740991) .
But, What is a Safe Integer anyway?
console.log(Math.pow(2, 53)); //9007199254740992 console.log(9007199254740992); //9007199254740992 console.log(9007199254740993); // 9007199254740992 Surprising!! console.log(9007199254740994); //9007199254740994 fine ! console.log(9007199254740995); // 9007199254740996
Hence you require
There are other new Math and Number related properties and Methods that ES6 has introduced and I would recommend that you try those out too along with the
Number.isInteger(); and the
Number.isSafeInteger() methods. Do let us know if you learned anything new today.