This post will discuss how to verify whether a value is an integer in JavaScript.

1. Using Number.isInteger() function

A simple solution is to use the Number.isInteger() function, which is a built-in function that returns true if the given value is an integer, and false otherwise. To use this function, we need to pass the value that we want to check as an argument.

Download  Run Code

 
Note that this function returns false for NaN or Infinity and returns true for floating-point numbers, which can be represented as an integer. e.g., 10.0. We may also use the Number.isSafeInteger() function to determine whether the specified number is a safe integer. Here’s polyfill provided by MDN for implementations that do not natively support it. We can insert it at the beginning of our scripts.

2. Using Modulo Operator

Another approach is to check for the remainder when the given number is divided by 1. If the remainder of dividing a number by 1 is 0, then the number is an integer; otherwise, it is not. We can use the modulo operator (%) for this purpose, which returns the remainder of dividing two numbers. To check for numeric values, place an additional check with unary plus (+) operator. For example:

Download  Run Code

3. Using parseInt() function

Finally, we can use the built-in function parseInt() which parses a string argument and returns an integer of the specified radix. To use this function, we need to pass the value that we want to check as a string argument, and optionally, the radix that we want to use as a second argument. The parseInt() function will return an integer if it can successfully parse the string argument, or NaN if it cannot. We can use the strict equality operator (===) check the result. For example:

Download  Run Code

That’s all about verifying whether a value is an integer in JavaScript.