16

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).

2
  • Their types are different, and so are the contexts in which they are usually used. Commented May 13, 2018 at 21:20
  • @Bergi yes I understand that, but I was hoping for a more detailed answer. I’m asking this with novice users in mind too. Commented May 13, 2018 at 21:22

1 Answer 1

31

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 undefined is the default value used when accessing things that don't exist
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.