How to Check if Number is Integer in JavaScript
In JavaScript, you can check if a number is an integer using
Number.isInteger(value), which returns true if the value is an integer and false otherwise. This method is the most reliable and modern way to perform this check.Syntax
The syntax to check if a value is an integer is simple:
Number.isInteger(value): Returnstrueifvalueis an integer, otherwisefalse.
Here, value is the number you want to test.
javascript
Number.isInteger(value)Example
This example shows how to use Number.isInteger() to check different values:
javascript
console.log(Number.isInteger(25)); // true console.log(Number.isInteger(25.0)); // true (25.0 is treated as 25) console.log(Number.isInteger(25.5)); // false console.log(Number.isInteger('25')); // false (string, not number) console.log(Number.isInteger(NaN)); // false console.log(Number.isInteger(Infinity)); // false
Output
true
true
false
false
false
false
Common Pitfalls
Some common mistakes when checking for integers:
- Using
typeofalone does not check if a number is integer. - Comparing with
parseIntcan be misleading because it converts strings. Number.isInteger()only returnstruefor numbers of typenumber, not strings.
Here is a wrong and right way:
javascript
// Wrong way: using typeof only const value = 25.5; console.log(typeof value === 'number'); // true but value is not integer // Right way: use Number.isInteger console.log(Number.isInteger(value)); // false
Output
true
false
Quick Reference
Summary tips for checking integers in JavaScript:
- Use
Number.isInteger(value)for a reliable check. - Remember it returns
falsefor non-number types. - Do not rely on
typeofor string conversions.
Key Takeaways
Use Number.isInteger(value) to check if a value is an integer in JavaScript.
Number.isInteger returns false for non-number types and decimal numbers.
Avoid using typeof or string parsing to check for integers.
Number.isInteger treats 25 and 25.0 as integers because they are the same number.