One of the easiest ways we can use JavaScript to check if a variable is a number is by using the JavaScript typeof Operator in an if conditional statement.
if ( typeof someVariable == "number" ){
//The variable IS a number
}
In the code above, someVariable is the variable that we want to check to see if it is a number. typeof someVariable will return “number” if the variable is a number, and therefore the conditional statement will be true.
We can put this code in a function to make checking if a variable is a number very simple.
Here is the function:
function isNumber(variable){
if ( typeof variable == "number" ){
return true;
} else {
return false;
}
};
Our function simply returns true if the variable you enter is a number, and false if not.
Now let’s show some examples of this function is use:
function isNumber(variable){
if ( typeof variable == "number" ){
return true;
} else {
return false;
}
};
var variable1 = 1234;
var variable2 = -853;
var variable3 = "1234";
var variable4 = 156.430393;
var variable5 = 0045865;
var variable6 = .00098;
console.log(isNumber(variable1));
console.log(isNumber(variable2));
console.log(isNumber(variable3));
console.log(isNumber(variable4));
console.log(isNumber(variable5));
console.log(isNumber(variable6));
#Output:
true
true
false
true
true
true
Hopefully this article has been useful for you to learn how to use JavaScript to check if a variable is a number.