11

what is NaN, Object or primitive?

NaN - Not a Number

kapa
  • 77,694
  • 21
  • 158
  • 175
DuduAlul
  • 6,313
  • 7
  • 39
  • 63

4 Answers4

15

It's a primitive. You can check in a number of ways:

  • typeof NaN gives "number," not "object."

  • Add a property, it disappears. NaN.foo = "hi"; console.log(NaN.foo) // undefined

  • NaN instanceof Number gives false (but we know it's a number, so it must be a primitive).

It wouldn't really make sense for NaN to be an object, because expressions like 0 / 0 need to result in NaN, and math operations always result in primitives. Having NaN as an object would also mean it could not act as a falsey value, which it does in some cases.

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
9

NaN is a primitive Number value. Just like 1, 2, etc.

kapa
  • 77,694
  • 21
  • 158
  • 175
2

NaN is a property of the global object.

The initial value of NaN is Not-A-Number — the same as the value of Number.NaN. In modern browsers, NaN is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it.

It is rather rare to use NaN in a program. It is the returned value when Math functions fail (Math.sqrt(-1)) or when a function trying to parse a number fails (parseInt("blabla")).

Reference

kapa
  • 77,694
  • 21
  • 158
  • 175
Katti
  • 2,013
  • 1
  • 17
  • 31
0

Would like to add some observations about NaN that intrigued me:

  1. typeof(NaN) returns 'number', but isNaN(NaN) returns true

Funny.

Also,

  1. isNaN(10) and isNaN('10') both return false

  2. isNaN('') returns false, but isNaN('any alphabetical string') returns true

  3. isNaN(true) and isNaN(false) return false. So boolean values are also considered as a number by isNaN function.

Vaibhav Chobisa
  • 131
  • 1
  • 4