NaN in JavaScript

NaN (Not-a-Number) is a special numeric value used when a JavaScript operation cannot produce a meaningful numeric result. It has unusual equality behavior: `NaN === NaN` is false.

`NaN` belongs to JavaScript's `number` type, despite its name suggesting that it is not numeric. It commonly appears when a numeric operation receives an invalid value, such as `Number("hello")`, or when a calculation produces an undefined numeric result.

A key property is that `NaN` is not equal to itself. Therefore, `value === NaN` cannot be used to test whether a value is NaN. Use `Number.isNaN(value)` when you specifically want to check for the actual NaN value.

`Number.isNaN()` does not coerce its argument before testing. This makes it different from the global `isNaN()`, which first converts its argument to a number and can therefore produce surprising results for non-numeric values.

NaN also propagates through many arithmetic operations. Once a calculation becomes NaN, further arithmetic involving that result generally remains NaN, so detecting and handling it early can prevent invalid values from spreading through an application.

Key points

Interview questions

What is the difference between `Number.isNaN()` and `isNaN()`?

`Number.isNaN()` checks whether its argument is actually the NaN value and does not perform type coercion. The global `isNaN()` first converts its argument to a number and then checks whether the result is NaN. For example, `isNaN("hello")` is true, while `Number.isNaN("hello")` is false. For most code that specifically needs to identify NaN values, `Number.isNaN()` is the clearer choice.

What is NaN in JavaScript?

NaN means Not-a-Number and is a special value in JavaScript's `number` type. It is commonly produced when a numeric conversion or operation cannot produce a valid number. Despite its name, `typeof NaN` is `"number"`. It also has unusual comparison behavior because it is not equal to itself.

Why does `NaN === NaN` return false?

NaN follows IEEE 754 floating-point semantics in which NaN is unordered and does not compare equal to any value, including another NaN. As a result, ordinary equality cannot reliably detect it. JavaScript therefore provides `Number.isNaN()` for an explicit NaN check.

How can NaN enter a frontend application's data flow?

It can appear when converting invalid user input with `Number()`, parsing unsuitable data, or performing calculations with invalid numeric operands. Once produced, NaN can propagate through later arithmetic and eventually reach UI state, formatting, or API payloads. Frontend code should validate input and check conversion results at appropriate boundaries. Keeping numeric validation close to the point where external data enters the application makes failures easier to diagnose.