JavaScript – Understanding Undefined and Its Uses

javascriptlanguage-design

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

  • the type undefined that can have only one value.
  • the variable 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 type undefined, and that value is stored in the variable undefined. That value has NO literal representation -- for example, number values 1, 100, 1e-1 are all literals of type number, but the value stored in the variable undefined has no literal form.

  • undefined is a variable, just a normal variable, that JavaScript declares and assigns it the value of type undefined in the global scope. So you can do all the following...

  typeof undefined;                       // "undefined"

  undefined = 100;
  typeof undefined;                       // "number"

  undefined = void 0;
  typeof undefined;                       // "undefined"

  window.undefined === undefined;         // true
  window.undefined === void 0;            // true
  
  • if you don't want to use the variable undefined, you can generate the value of type undefined by the expression void 0 -- whose sole purpose is to return a value of type undefined.

...can anyone please explain to me why this thing has been inserted into JavaScript...

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.

...we have null value...

Although null can do things undefined does, it is more or less related to objects rather than scalars. Indeed, JavaScript considers null itself an object -- typeof null returns "object".

In my opinion, the bottom line is to NOT try to reason the absolute purposes of undefined and null -- and use them in your code intelligibly, so that your code is readable, maintainable and reusable.

Related Topic