In JavaScript, you can use the isNaN() function to determine if a value is "not a number" (NaN). This function returns a Boolean value indicating whether the provided value is NaN or not.
Here is an example of how you might use the isNaN() function:
console.log(isNaN(3)); // outputs "false" console.log(isNaN("hello")); // outputs "true" console.log(isNaN("4")); // outputs "false"
You can also use it with a variable to check if the value is a number or not, like this:
let myValue = "3"; let myNumber = 6; let myString = "seven"; if(isNaN(myValue)){ console.log("MyValue is not a number") } else{ console.log("MyValue is a number") } if(isNaN(myNumber)){ console.log("MyNumber is not a number") } else{ console.log("MyNumber is a number") } if(isNaN(myString)){ console.log("MyString is not a number") } else{ console.log("MyString is a number") }
It will output:
MyValue is a number MyNumber is a number MyString is not a number
It's important to note that isNaN() function has some quirks, If the argument is of a type that can be converted to a number, the function attempts to do so. For example, if you pass a string "3" it will return false, but if you pass a string "not a number" it will return true. Also If the argument is of type undefined or String, the function returns true if the argument is not convertible to a number.
One way to avoid the quirks of isNaN() function is by using Number.isNaN() which was introduced in ECMAScript 6, it returns true only if the value passed to it is exactly NaN without type conversion.
Keep in mind that isNaN is a global function, you don't need to include any import or import it from a package, It's available for you to use in all your javascript codes.