How To Check If A Value Is An Integer In JavaScript

Check if a Value is an Integer in JavaScript

In javascript, there are many ways to check if a value is an integer in JavaScript. In this tutorial, I would like to introduce some common ways like the typeof, isInteger(), and parseInt() to check a variable is an integer or not. Follow the article to understand and use these methods.

Check If A Value Is An Integer In JavaScript

Method 1: Use typeof operator

The typeof operator helps you check if a variable is an integer. Not only that, but it also helps you check many other value types like an object, string, ..etc. With the typeof operator, it will have to compare the returned string with "number", let’s check the below example:


var myNum = 8;
var result = typeof myNum == "number" && myNum % 1 == 0 ? true : false;

? : is a ternary operator. In the above syntax, the ternary operator is used to compare the result of typeof with the string "number" and check the given number is divisible by one or not. If both conditions are true, the program will return true and false otherwise. To better understand, run the above example with two numbers as two different value types and follow the results. Below is my example:

var myNum1 = 8;
var myNum2 = 8.1;

var resultNum1 = typeof myNum1 == "number" && myNum1 % 1 == 0 ? true : false;
var resultNum2 = typeof myNum2 == "number" && myNum2 % 1 == 0 ? true : false;




We see that num2 = 8.1 is a non-integer float, so we get a false back, and num1 is an integer, so we have a true return value. You can try with other values ​​like strings or objects to check and better understand this method.

Method 2: Use isInteger() method

isInteger() is a built-in method in javascript used to check the value to be checked as an integer or not, if true, it will return true, and another data type will return false.




  • checkValue: This is a value that you want to check


var num1 = 8;
var num2 = [];




In this example, I pass in an object to check if it is an integer, and the return value is no different from the two examples of the two methods above.


The above article shows us that check if a value is an integer in JavaScript has many ways to do it, from easy to complex, from quick to thorough. Let’s choose the method that you find most suitable for you. I hope this article helps to you.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *