How to use the isNaN() method In Javascript
The isNaN() method in JavaScript is used to check whether the passed value is Not a Number. It returns true if the passed number is Not a Number. Otherwise, it will return false.
NOTE: The isNaN() method can successfully parse a numeric string(“123”) as a number and returns false, which means it considers a numeric string as a number.
Syntax:
isNaN(testingValue);
Example: The below code implements the isNaN() method to check whether the passed value is a number.
function isNumber(value){
try{
if(isNaN(value)){
throw new Error("Passed value is not a number");
}
console.log("Passed value is a number");
}
catch(error){
console.log("An error occurred: ", error.message);
}
}
isNumber(55);
isNumber("58");
isNumber("w3wiki");
Output
Passed value is a number Passed value is a number An error occurred: Passed value is not a number
How to Check if a Value is a Number in JavaScript ?
To check if a value is a number in JavaScript, use the typeof operator to ensure the value’s type is ‘number’. Additionally, functions like Number.isFinite() and !isNaN() can verify if a value is a valid, finite number.
We can use the below methods to check whether the value is a number or not:
Table of Content
- Using the isNaN() method
- Using the typeof operator
- Using the Number.isInteger() method
- Using the Number.isFinite() method