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
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)
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