How do I check if a variable is an integer in JavaScript, and throw an alert if it isn't? I tried this, but it doesn't work:
<html>
<head>
<script type="text/javascript">
var data = 22;
alert(NaN(data));
</script>
</head>
</html>
Assuming you don't know anything about the variable in question, you should take this approach:
To put it simply:
Besides,
Number.isInteger()
. MaybeNumber.isSafeInteger()
is another option here by using the ES6-specified.To polyfill
Number.isSafeInteger(..)
in pre-ES6 browsers:Use the
|
operator:So, a test function might look like this:
Be careful while using
empty string ('') or boolean (true or false) will return as integer. You might not want to do that
Number.isInteger(data)
build in function in the browser. Dosnt support older browsers
Alternatives:
However, Math.round() also will fail for empty string and boolean
From http://www.toptal.com/javascript/interview-questions:
Found it to be the best way to do this.