type checking in javascript type checking in javascript javascript javascript

type checking in javascript


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)


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 = 3js> Number.isInteger(x)truejs> var y = 3.1js> Number.isInteger(y)false


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 doesMath.pow(2,50)+.1 == Math.pow(2,50)