How to check if a value is NaN in JavaScript
Checking for NaN values is crucial for input validation, error handling, mathematical operations, and implementing robust features like form validation or data processing in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented NaN checking extensively in components like calculators, form validators, and data processors where detecting invalid numeric operations prevents errors and ensures reliable functionality.
From my extensive expertise, the most accurate and recommended approach is using Number.isNaN()
, which performs a strict NaN check without type coercion.
This method is precise, avoids common pitfalls of the older isNaN()
function, and provides reliable detection of actual NaN values.
Use Number.isNaN()
to check if a value is specifically NaN without type coercion.
const result = 0 / 0
const isNotANumber = Number.isNaN(result)
// Result: true
const stringValue = 'hello'
const isStringNaN = Number.isNaN(stringValue)
// Result: false
The Number.isNaN()
function returns true
only if the value is actually NaN, without attempting to convert other types. In the first example, 0 / 0
produces NaN, so Number.isNaN(result)
returns true
. In the second example, even though 'hello'
is not a number, Number.isNaN('hello')
returns false
because the string is not literally NaN. This strict behavior prevents false positives that occur with the global isNaN()
function, which converts values to numbers before checking.
Best Practice Note:
This is the same approach we use in CoreUI components for validating calculation results, processing form inputs, and ensuring data integrity across our component library.
Avoid the global isNaN()
function as it converts values first: isNaN('hello')
returns true
, which is often unexpected. For checking if a value can be converted to a valid number, use isNaN(Number(value))
. The Number.isNaN()
method is supported in all modern browsers and provides the most accurate NaN detection.