The Number isInteger() method
By Flavio Copes
Learn how the JavaScript Number.isInteger() method checks whether a value is an integer, returning false for decimals, strings, booleans, objects, and arrays.
Number.isInteger() returns true if the value you pass is an integer. Anything else, booleans, strings, objects, arrays, returns false:
Number.isInteger(1) //true
Number.isInteger(-237) //true
Number.isInteger(0) //true
Number.isInteger(0.2) //false
Number.isInteger('Flavio') //false
Number.isInteger(true) //false
Number.isInteger({}) //false
Number.isInteger([1, 2, 3]) //false
Why do we need it?
Before this method arrived with ES2015, checking for an integer meant writing something like typeof value === 'number' && value % 1 === 0. That works, but it’s easy to get wrong.
Number.isInteger() does the check in one call. A common use is validating a quantity before using it:
const quantity = 3
if (Number.isInteger(quantity)) {
//safe to use as an item count
}
It does not convert values
The method never converts what you pass to a number. The string '5' is not an integer, it’s a string:
Number.isInteger('5') //false
Number.isInteger(5) //true
This is the big difference from a check like value % 1 === 0, where JavaScript would convert '5' to 5 first and give you true.
What about edge cases?
A number with a fractional part of zero counts as an integer:
Number.isInteger(5.0) //true
Number.isInteger(5e3) //true, it's 5000
NaN and Infinity are numbers, but not integers:
Number.isInteger(NaN) //false
Number.isInteger(Infinity) //false
Very large numbers can surprise you. JavaScript can’t store every huge value precisely, so some decimals round to the nearest integer before the check runs:
Number.isInteger(5.0000000000000001) //true
The literal becomes 5 before isInteger() ever sees it. If you work with numbers that big, look at Number.isSafeInteger(), which also checks the value is small enough to be stored exactly.
BigInt values fail the check too, even when they hold whole numbers. A BigInt is a different type, not a number:
Number.isInteger(10n) //false
A common pitfall with form input
Values coming from an HTML input are always strings. This check fails even when the user typed a whole number:
const input = '42'
Number.isInteger(input) //false
Convert first, then check:
Number.isInteger(Number(input)) //true
Number('42') gives you 42, and the check passes. Skip the conversion and every value from a form will fail validation.
Related posts about js: