To check if a value is NaN (Not-a-Number) in JavaScript, you can use the isNaN()
function. This function returns true
if the value is NaN and false
if it is not. Here’s how you can use it:
var value = /* some value */;
if (isNaN(value)) {
console.log('The value is NaN.');
} else {
console.log('The value is not NaN.');
}
However, keep in mind that isNaN()
will first try to convert the value to a number if it isn’t already. This means that isNaN('text')
will return true
because ‘text’ is not a number.
If you want to check specifically for the NaN value (not just any non-numeric value), and you’re dealing with a scenario where the value is expected to be numeric, you might use the Number.isNaN()
function instead, which does not coerce the value to a number:
var value = /* some value */;
if (Number.isNaN(value)) {
console.log('The value is specifically NaN.');
} else {
console.log('The value is not NaN.');
}
Number.isNaN()
is a more accurate way to check if a value is exactly NaN since it does not coerce the value to a number before the check. This can be particularly useful when dealing with arithmetic operations that might result in NaN, and you want to distinguish between non-numeric strings and actual NaN results from calculations.