3 Ways to Check if a Value is a Number in JavaScript
In this tutorial, we'll explore three different ways to check if a value is a number in JavaScript, using the isInteger()
, typeof()
, and isNaN()
methods.
The isInteger()
Method
The 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
The typeof
operator returns the data type of a value. If the value is a number, it returns "number" as the value:
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 isNaN()
function checks if a value is NaN (Not-a-Number). If isNaN(value)
returns false, the value is numeric:
var value = 2;
isNaN(value) // false
isNaN("Hello") // true
isNaN({}) // true
isNaN(2) // false
isNaN(2.4) // false
Conclusion
Using isInteger()
, typeof
, and isNaN()
methods, you can easily determine if a value is numeric in JavaScript. Each method has its specific use cases, making them versatile tools for type checking.
Comments
There are no comments yet. Start the conversation!