Using undefined in JavaScript

August 10th, 2010

Working with JavaScript can definitely be painful, but I always love stumbling across interesting and strange features of the language. I just found wtfjs.com which led me to these two answers on stackoverflow.

The first answer made me realize that undefined is not a keyword in JavaScript; it actually is a type that also happens to have a global variable with the same name. This means that you can change the value of undefined (the global variable) to be something else.

>>> typeof undefined === "undefined"
true
>>> undefined = 42
42
>>> typeof undefined === "undefined"
false

And, like shown above, the correct way to check if a variable is undefined is by using typeof.

>>> var myVariable;
>>> typeof myVariable
"undefined"
>>> myVariable = 1;
1
>>> typeof myVariable
"number"

The second feature, is something that I often used but had no idea why it actually worked: void(0).

<a href="javascript:void(0)">do nothing</a>

According to Breton’s excellent explanation, void is actually a prefix operator. When you prefix any expression with void, the result evaluates to undefined. So, using our correct method for checking undefined above you get this in the console:

>>> typeof void(0) === "undefined"
true

Awesome!

Leave a Reply

In order to provide better answers to questions, please read the following before posting a comment:

  1. General question about SharePoint? Please ask a question at SharePoint StackExchange
  2. Comment or feedback specific to this post only? Please post a comment below