How to check type is number in JavaScript?
Table of Contents
- Introduction
- 1. Using
typeof
- 2. Using
isNaN()
- 3. Using
Number.isNaN()
- 4. Using
Number.isFinite()
- 5. Combining Checks
- Conclusion
Introduction
In JavaScript, determining the type of a variable is crucial for ensuring that your code functions as expected. When working with numbers, it’s essential to check whether a variable is indeed a number, especially since JavaScript has a flexible type system. This guide will cover various methods to check if a variable is a number in JavaScript, including typeof
, isNaN
, and Number.isFinite
.
1. Using typeof
The simplest way to check if a variable is a number is by using the typeof
operator. This operator returns a string that indicates the type of the unevaluated operand.
Example
In this example, typeof num
returns 'number'
, confirming that num
is a number. However, it's worth noting that typeof NaN
also returns 'number'
, which can lead to confusion.
2. Using isNaN()
The isNaN()
function determines whether a value is NaN
(Not a Number). It coerces the value to a number and returns true
if it is NaN
, making it useful for identifying non-numeric values.
Example
While isNaN()
is helpful, it can produce false positives since it attempts to convert values to numbers.
3. Using Number.isNaN()
To avoid the pitfalls of coercion with isNaN()
, you can use Number.isNaN()
, which checks if a value is exactly NaN
without coercion.
Example
This method is more reliable when checking for NaN
.
4. Using Number.isFinite()
Another way to check if a variable is a number is by using Number.isFinite()
. This method returns true
if the value is a finite number, which effectively checks if the variable is a number and not NaN
or infinite.
Example
Using Number.isFinite()
ensures that the variable is both a number and not an infinite value.
5. Combining Checks
For a comprehensive solution, you can combine typeof
, isNaN
, and Number.isFinite()
to create a robust number-checking function.
Example
This function checks that the value is of type number
, not NaN
, and finite.
Conclusion
Checking if a variable is a number in JavaScript can be accomplished using various methods, each with its nuances. The typeof
operator is a straightforward approach, while isNaN()
and Number.isFinite()
provide more robust validation against common pitfalls. By understanding these methods and their limitations, you can effectively validate data types and ensure the correctness of your JavaScript code.