How to check if a variable is an integer or not in javascript

These short tutorials cover how to check whether a given declared variable is an integer or not in JavaScript.

For example, the Integer variable always contains numeric digits.

How to check if a variable is an integer in JavaScript?

There are multiple ways we can do it.

  • use isNan method

One way to use isNan parseInt and parseFloat methods is to check given variable is a number.

isNan(): used to check given variable is not a number parseInt(): used to convert a string or number to a number with a base of number, hexadecimal. parseFloat(): used to convert a string float to a number.

Here is a code

function checkVariableNumber(arg) {
  return !isNaN(arg) && parseInt(arg) == parseFloat(arg);
console.log(checkVariableNumber(256)); //true
console.log(checkVariableNumber("abc")); //false
console.log(checkVariableNumber("11")); //true
  • use regular expression

the regular expression contains digits 0-9 and the symbol d only allows digits

Here is an example of checking integers or numbers using regular expressions.

var number = /^[0-9]\d*$/;

console.log(number.test(11)); //true
console.log(number.test("11")); //true
console.log(number.test("abc")); //false
console.log(number.test("1b")); //false
  • use ES6 Number isInteger Method

EcmaScript 2015 introduced isInteger() method in the Number object.

It returns true if the parameter is an integer. else it returns false. Syntax:


the parameter can be string or number.

console.log(Number.isInteger(1)); //true
console.log(Number.isInteger("")); //false
console.log(Number.isInteger(21)); //true
console.log(Number.isInteger("")); //false
console.log(Number.isInteger("23")); //false

Since javascript runs in a client browser, All the latest browsers support this.

lodash isInteger method

if the application uses the lodash library, it is easy to check variable is an integer. It provides the lodash.isInteger function which takes one argument of numbers.

console.log(_.isInteger(21)); //true
console.log(_.isInteger("")); //false
console.log(_.isInteger("23")); //false