TomRed.net

  • Increase font size
  • Default font size
  • Decrease font size
Subscribe Bookmark and Share
Home Tutorials JavaScript JavaScript Identify if a variable is an Integer(Number) or not

JavaScript Identify if a variable is an Integer(Number) or not

User Rating: / 0
PoorBest 

There are hundreds or scripts writen to identify if an input variable is a number or correctly and integer. Most of these involve complex if statements or even regex. All of these ways while accurate are mostly unnecessarily complex. JavaScript provides a very simple function that can answer this with a boolean [true|false].

isNaN

isNaN() is a function whos name literally means is Not A Number. When a value to be tested is a number this will return false. If the value being tested in not a number it returns true. This immediately offers two options to developers one looking to make sure a value is a number and one looking to make sure a value is not a number.

<script type="text/javascript">
var test1="500";
var test2="something interesting";

alert(isNaN(test1));
alert(isNaN(test2));
</script>

The output of the code above will be:

false
true

Number

Number is a further method which along with JavaScript Converting Strings to Int for Addition not Concatenation will return NaN (not a number) when operated against none numeric values. The value can then be tested against to see whether it returns NaN before continuing. I have altered the example above to use the Number method here:

<script type="text/javascript">
var test1="500";
var test2="something interesting";

alert(Number(test1));
alert(Number(test2));
</script>

The output of the code above will be:

500
NaN

As you can see it is easier and more direct to use the isNaN method then process and then test a value.