JavaScript developers often need to check whether a value is a number or not. There are several methods in JavaScript that can help determine if a variable is a number or not.
In this article, we will discuss the best ways to check if a value is a number in JavaScript, including the isNaN()
method, the typeof
operator, and the Number.isInteger()
method. By the end of this article, you will have a clear understanding of how to identify numbers in JavaScript.
1. isNaN()
The first method, we are going to use is isNaN()
.
The method isNaN()
stands for "is-not-a-number". If a number is passed as a parameter to it, the method will return false.
Here are a few examples with comments describing the output of the isNaN()
method.
const x = 4;
const string = "Hello World";
isNaN(x) // false
isNaN(string) // true
isNaN({}) // true
isNaN(Math.PI) // false
2. "typeof" Operator
Another way to determine if the input is a number is to use the typeof
operator.
It returns number
string when you use it on a number.
For example,
const x = 4;
typeof x; // 'number'
typeof Math.PI; // 'number'
typeof "John" // 'string'
So, you can apply a conditional check to this,
const x = 4;
if(typeof x === 'number'){
// Logic goes here
}else{
// X is not a number
}
3. Number.isInteger()
The Number.isInteger()
method returns true
if an integer value is passed as a parameter.
Otherwise, it returns false
Please note: that Number.isInteger() is only applicable for integer data types. It will accurately return true for 4 but will return false for non-integer values like 3.14. You should only use this method if you specifically need to validate integer data types.
Number.isInteger(4); // true
const x = 20;
Number.isInteger(x) // true
Conclusion
In conclusion, JavaScript offers several ways to determine if a variable is a number or not. The isNaN()
method checks if a value is not a number, the typeof
operator can be used to check if a value is a number, and the Number.isInteger()
method can be used to validate integer data types specific. It is important to choose the appropriate method based on the specific needs of the program.
Top comments (1)
Throw
BigInt
s into the mix and things get a little more complicated. Technically, they are 'numbers' - but notNumber
s to JavaScript. Also, callingisNaN
on aBigInt
will give you an error: