How to check if a Value is an Integer in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 16 20211 min read

banner

Photo by Chema Photo

Check if a Value is an Integer in JavaScript #

To check if a value is an integer, call the Number.isInteger() method, passing it the value as a parameter. The method returns true if the provided value is an integer, otherwise it returns false.

index.js
console.log(Number.isInteger(1)); // ๐Ÿ‘‰๏ธ true console.log(Number.isInteger(1.5)); // ๐Ÿ‘‰๏ธ false console.log(Number.isInteger('1')); // ๐Ÿ‘‰๏ธ false console.log(Number.isInteger(-10)); // ๐Ÿ‘‰๏ธ true

The only parameter the Number.isInteger method takes is the value we want to test for being an integer.

The method returns true if the passed in value:

  • is an integer
  • is a float, that can be represented as an integer

Here are examples of floats that can be represented as integers:

index.js
const a = 10.0; const b = 10.000000000000000123; console.log(Number.isInteger(a)); // ๐Ÿ‘‰๏ธ true console.log(Number.isInteger(b)); // ๐Ÿ‘‰๏ธ true

If the Number.isInteger method is called with NaN or Infinity, it returns false.

index.js
console.log(Number.isInteger(NaN)); // ๐Ÿ‘‰๏ธ false console.log(Number.isInteger(Infinity)); // ๐Ÿ‘‰๏ธ false

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee