{

How to check whether a given 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 and parseInt and parseFloat methods are to check given variable is a number.

isNan(): uses to check given variable is not a number parseInt(): uses to convert a string or number to a number with a base of number, hexadecimal. parseFloat(): uses 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 symbol d to only allow digits

Here is an example check integer or number using regular expression.

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 Number object.

Syntax:

Number.isInteger(parameter)

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 lodash.isInteger function which takes one argument of numbers.

console.log(_.isInteger(21))//true
console.log(_.isInteger(""))//false
console.log(_.isInteger("23"))//false
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.