85

How can I check if a variable is currently an integer type? I've looked for some sort of resource for this and I think the === operator is important, but I'm not sure how to check if a variable is an Integer (or an Array for that matter)

sova
  • 5,468
  • 10
  • 40
  • 48
  • 9
    == checks for value equality, === checks for value and type equality. "1" == 1 would be true, "1" === 1 would be false – Kai Dec 22 '10 at 23:22
  • you can consider using a very small library like [Not](https://github.com/calvintwr/you-are-not). Solves all problems. – Calvintwr Jun 02 '20 at 19:02

8 Answers8

133

A variable will never be an integer type in JavaScript — it doesn't distinguish between different types of Number.

You can test if the variable contains a number, and if that number is an integer.

(typeof foo === "number") && Math.floor(foo) === foo

If the variable might be a string containing an integer and you want to see if that is the case:

foo == parseInt(foo, 10)
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 2
    you can also use isNaN(foo) http://www.w3schools.com/jsref/jsref_NaN.asp instead of typeof – m4tt1mus Dec 22 '10 at 23:29
  • 6
    *"it doesn't distinguish between different types of Number"* That's because there are no different types of Number. *All* numeric values in JS are 64-bit floats. – NullUserException Oct 07 '12 at 06:54
  • 1
    @NullUserException — That's what I said. – Quentin Oct 07 '12 at 10:09
  • If you're using jQuery, you can use it's $.type() function. Ex. $.type("1") # => "string" – Andrei Jul 09 '13 at 21:44
  • One could also use constructor equivalence: `foo.constructor === Number`. One could then throw in the Math.floor or parseInt check to verify the Number is actually an int. The benefit of this is you are actually checking a concrete type name, rather than a string, however that may not quite carry the weight it does in a strongly typed language. – jrista Nov 02 '13 at 06:09
  • You can also check if a number x is a valid array index, i.e. a 32-bit integer with x === (x|0). The binary operator casts to a 32-bit int internally, so if casting to an int and then back to a double leaves the value the same, it's a valid 32-bit int. Anything out of range or the wrong type gets cast to 0. – Mike Stay Jan 24 '14 at 04:26
  • Beware, `typeof new Number(foo)` is "object" – yhpark Feb 17 '14 at 15:04
  • 3
    This answer should be updated as it's inconsistent with the ECMAScript 2015 [*Number.isInteger*](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-isinteger) function. It should return false for *Infinity*, not true. – RobG Nov 22 '15 at 23:20
  • A functional way of type checking https://stackoverflow.com/a/64794158/1948585 – user1948585 Nov 12 '20 at 03:01
20

These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:

js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false
dat
  • 1,580
  • 1
  • 21
  • 30
7

A number is an integer if its modulo %1 is 0-

function isInt(n){
    return (typeof n== 'number' && n%1== 0);
}

This is only as good as javascript gets- say +- ten to the 15th.

isInt(Math.pow(2,50)+.1) returns true, as does Math.pow(2,50)+.1 == Math.pow(2,50)

Liam
  • 27,717
  • 28
  • 128
  • 190
kennebec
  • 102,654
  • 32
  • 106
  • 127
2

A clean approach

You can consider using a very small, dependency-free library like Issable. Solves all problems:

// at the basic level it supports primitives
let number = 10
let array = []
is(number).number() // returns true
is(array).number() // throws error

// so you need to define your own:
import { define } from 'issable'
// or require syntax
const { define } = require('issable')

define({
    primitives: 'number',
    nameOfTyping: 'integer',
    toPass: function(candidate) {
        // pre-ECMA6
        return candidate.toFixed(0) === candidate.toString()
        // ECMA6
        return Number.isInteger(candidate)
    }
})
is(4.4).custom('integer') // throws error
is(8).custom('integer') // returns true

If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.

function test (string, boolean) {
    // any of these below will throw errors to protect you
    is(string).string()
    is(boolean).boolean()

    // continue with your code.
}
Calvintwr
  • 8,308
  • 5
  • 28
  • 42
1

I know you're interested in Integer numbers so I won't re answer that but if you ever wanted to check for Floating Point numbers you could do this.

function isFloat( x )
{
    return ( typeof x === "number" && Math.abs( x % 1 ) > 0);
}

Note: This MAY treat numbers ending in .0 (or any logically equivalent number of 0's) as an INTEGER. It actually needs a floating point precision error to occur to detect the floating point values in that case.

Ex.

alert(isFloat(5.2));   //returns true
alert(isFloat(5));     //returns false
alert(isFloat(5.0));   //return could be either true or false
Dan
  • 2,625
  • 7
  • 39
  • 52
1

You may also have a look on Runtyper - a tool that performs type checking of operands in === (and other operations).
For your example, if you have strict comparison x === y and x = 123, y = "123", it will automatically check typeof x, typeof y and show warning in console:

Strict compare of different types: 123 (number) === "123" (string)

vitalets
  • 4,675
  • 1
  • 35
  • 35
0

Quite a few utility libraries such as YourJS offer functions for determining if something is an array or if something is an integer or a lot of other types as well. YourJS defines isInt by checking if the value is a number and then if it is divisible by 1:

function isInt(x) {
  return typeOf(x, 'Number') && x % 1 == 0;
}

The above snippet was taken from this YourJS snippet and thusly only works because typeOf is defined by the library. You can download a minimalistic version of YourJS which mainly only has type checking functions such as typeOf(), isInt() and isArray(): http://yourjs.com/snippets/build/34,2

Chris West
  • 885
  • 8
  • 17
0

Try this code:

 alert(typeof(1) == "number");
Liam
  • 27,717
  • 28
  • 128
  • 190
eSniff
  • 5,713
  • 1
  • 27
  • 31