Published on

The JavaScript's `NaN` property

The JavaScript NaN property stands for Not-a-Number. It is a value that typically represents the result of an undefined or unrepresentable mathematical operation.

How Do You Encounter NaN?

NaN typically appears in scenarios where arithmetic operations go awry. Here are a few common culprits:

  • Undefined Arithmetic: Performing arithmetic operations with non-numeric operands often leads to NaN. For example, 0/0 or Math.sqrt(-1).
let result = 0 / 0 // NaN
let sqrt = Math.sqrt(-1) // NaN
  • Parsing Non-Numeric Values: When you try to convert a string that doesn't represent a number into a number, it results in NaN.
let parsed = parseInt('not a number') // NaN
  • Invalid Date Operations: Operations on an invalid Date object also result in NaN.
let invalidDate = new Date('not a date').getTime() // NaN
  • Math Functions on Non-Numbers: Certain Math functions will return NaN when given non-numeric inputs.
let log = Math.log(-1) // NaN

The Uniqueness of NaN

NaN is a unique character in the JavaScript narrative. It's the only value in JavaScript that is not equal to itself. You can't use the usual equality checks (== or ===) to detect NaN. Instead, you'll need to call in a specialist: Number.isNaN(value).

console.log(NaN === NaN) // Output: false
console.log(NaN == NaN) // Output: false

Dealing with NaN

Encountering NaN can be a sign that something's gone amiss in your calculations. It's a flag, alerting you to look closer at your code.

When dealing with operations where NaN could emerge, it's wise to add checks or use Number.isNaN() to handle these cases gracefully.