3 Ways to Check if a Value is a Number in JavaScript
In this article, we'll explore three different ways of checking if a value is a number in JavaScript. That's right, three! It might seem like this is overkill, but there's never anything wrong with exploring options.
The Number isInteger()
Method
The Number isInteger()
method in JavaScript accepts a single parameter, the value being tested. The method returns true if the value is numeric, and false if it isn't:
Number.isInteger(123) - true
Number.isInteger(-123) - true
Number.isInteger("123") - false
Number.isInteger(4 / 2) - true
Number.isInteger(5 / 2) - false
The typeof()
Operator
Another way of checking if a value is a number in JavaScript is by using testing with the typeof()
operator. Instead of returning a boolean, the value's type is returned:
typeof(123) - number
typeof(-123) - number
typeof("123") - string
typeof([123]) - object
You can also run a comparison by writing a conditional statement:
var value = 123;
if (typeof(value) === "number") {
// value is numeric
}
The isNaN()
Global Variable
The final way we'll check if a value is a number in JavaScript is by using isNaN()
, a global variable that's assigned to the window
object in the browser. Unlike the isInteger()
method, if the value is false, then it's numeric. If true, then it's not numeric:
var value = 2;
isNaN(value) - false
isNaN("Hello") - true
isNaN({}) - true
isNaN(2) - false
isNaN(2.4) - false
Conclusion
Again, three different methods may seem like overkill, but this way you get to explore all the options available and can choose which method works best for you.
Comments
There are no comments yet. Start the conversation!