12

What is the difference between Null, NaN and undefined in JavaScript?

I have come across all three values, and have understood them to be “there isn’t anything here” in the context I found them- but I was hoping for a more detailed explanation as to why they occur, as well as what they mean in different contexts (for example- against an array, vs a class or variable).

Alex Mulchinock
  • 2,119
  • 1
  • 18
  • 25

1 Answers1

28

NaN: Not a number: As the name implies, it is used to denote that the value of an object is not a number. There are many ways that you can generate this error, one being invalid math opertaions such as 0/0 or sqrt(-1)

undefined: It means that the object doesn't have any value, therefore undefined. This occurs when you create a variable and don't assign a value to it.

null: It means that the object is empty and isn't pointing to any memory address.

Danyal Imran
  • 2,515
  • 13
  • 21
  • 7
    A bit more informally and concisely `NaN` - "not a valid number" usually after you did some operation that should produce one but couldn't. `undefined` - it *exists* but hasn't been given a value *yet*. `null` - it exists and it has deliberately been given an empty value. That's sort of the idea behind them - basically three different signifiers for "non-value". People can use them differently, if they want, of course but *generally* that's what they are understood as. – VLAZ May 13 '18 at 21:43
  • 1
    @vlaz `undefined` is the default value used when accessing things that *don't* exist – Bergi May 13 '18 at 21:59
  • 2
    @Bergi well, it depends on your definition there. To me it makes sense because if you do `obj.missingValue` the *object* exists even if the `missingValue` property doesn't. Similarly, doing `arr[42]` on an array that only has a single element yields `undefined` however `arr` itself exists. So, perhaps it might be more correct to say that you can *access* a given thing but it has not been given any value yet. – VLAZ May 13 '18 at 22:11