In JavaScript, there are two ways to check if a variable is a number :
- isNaN() – Stands for “is Not a Number”, if a variable is not a number, it returns true, else return false.
- typeof – If a variable is a number, it will return a string named “number”.
Using isNaN() Function
The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value equates to NaN. Otherwise, it returns false.
let num = 50;
if(isNaN(num)){
console.log(num + " is not a number");
}else{
console.log(num + " is a number");
}
let str = "javaguides";
if(isNaN(str)){
console.log(str + " is not a number");
}else{
console.log(str + " is a number");
}
Output:
50 is a number
javaguides is not a number
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.
Using typeof Operator
The typeof operator is a unary operator that returns a string representing the type of a variable.
Read more about typeof operator at https://www.javaguides.net/2019/05/javascript-typeof-operator-example.html
let num = 50;
if(typeof num == 'number'){
console.log(num + " is a number");
}else{
console.log(num + " is not a number");
}
Output:
50 is a number
Comments
Post a Comment
Leave Comment