In JavaScript, we have something called undefined. I said something, because I really don't know if it's a base class, or a built-in variable, or a keyword, or anything else. I just know that it's there.
To see it in action, you can simply write:
undefined;
typeof undefined;
Can anyone please explain to me why this thing has been inserted into JavaScript? We have null
value in this language, thus it shouldn't be something like null
. In other languages, when we don't know the value of a property or variable, we simply set it to null. Here we can do the same thing.
How we can use this thing in JavaScript?
Best Answer
There are TWO things you need to understand about undefined...
undefined
that can have only one value.undefined
Now read the following very carefully...
There are so many values of type
number
(10, 10.01, 1e1). But there can be only one value of typeundefined
, and that value is stored in the variableundefined
. That value has NO literal representation -- for example, number values1
,100
,1e-1
are all literals of type number, but the value stored in the variableundefined
has no literal form.undefined
is a variable, just a normal variable, that JavaScript declares and assigns it the value of typeundefined
in the global scope. So you can do all the following...undefined
, you can generate the value of typeundefined
by the expressionvoid 0
-- whose sole purpose is to return a value of typeundefined
.NO. Just like no one can explain why undeclared variables go to global scope instead of local. You just need to train yourself to smartly use it instead of trying to find justifications for it's existence.
Although
null
can do thingsundefined
does, it is more or less related toobjects
rather than scalars. Indeed, JavaScript considersnull
itself an object --typeof null
returns "object".In my opinion, the bottom line is to NOT try to reason the absolute purposes of
undefined
andnull
-- and use them in your code intelligibly, so that your code is readable, maintainable and reusable.