In JavaScript, you can check if a variable is a number or not using one of the following two ways:
-
Using isNaN()
function
-
Using typeof
operator
Let's see both the approach with code examples.
Using isNaN()
function
isNaN stands for "is Not a Number". This function takes one argument and returns True if the argument provided is not a number, and returns False if a numeric value is passed as argument to this function. Following is the syntax for this function:
isNaN(variable)
where, variable is the name of a variable which may or may not have a number value.
Let's take an example,
var num = 1;
var str = "Studytonight";
if(isNaN(str)) {
console.log(str + " is not a number");
}
if(!isNaN(num)) {
console.log(num + " is a number");
}
Output:
Studytonight is not a number
1 is a number
Note: In the second if
condition, we have used the not !
operator with isNaN()
function, to check if the variable passed is a number.
Using typeof
Operator
The typeof
operator can be used to see the type of a variable. For example, if we use the typeof
operator with a string value, it will return string and if we use the typeof
operator with a numeric value, it will return number as result.
var num = 1;
if(typeof num == "number") {
console.log(str + " is not a number");
}
else {
console.log(num + " is a number");
}
Output:
1 is a number
Time for an Example
Below, we have a running code example, where we have used both isNaN()
function and typeof
operator. Try running the code with different values for num
and str
variables.
Use the Run button to run the code.
You may also like: