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>
Why hasnt anyone mentioned
Number.isInteger()
?https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
Works perfectly for me and solves the issue with the
NaN
beginning a number.This will solve one more scenario (121.), a dot at end
My approach:
Use the === operator (strict equality) as below,
You can use a simple regular expression:
That depends, do you also want to cast strings as potential integers as well?
This will do:
With Bitwise operations
Simple parse and check
Short-circuiting, and saving a parse operation:
Or perhaps both in one shot:
Tests:
Here's the fiddle: http://jsfiddle.net/opfyrqwp/28/
Performance
Testing reveals that the short-circuiting solution has the best performance (ops/sec).
Here is a benchmark: http://jsben.ch/#/htLVw
If you fancy a shorter, obtuse form of short circuiting:
Of course, I'd suggest letting the minifier take care of that.