Using undefined in JavaScript
By Kit
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 <span class=“text”>undefined</span>
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 <span class=“text”>undefined</span>
(the global variable) to be something else.
true
>>> undefined = 42
42
>>> typeof undefined === "undefined"
false
And, like shown above, the correct way to check if a variable is <span class=“text”>undefined</span>
is by using <span class=“text”>typeof</span>
.
>>> 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: <span class=“text”>void(0)</span>
.
According to Breton’s excellent explanation, <span class=“text”>void</span>
is actually a prefix operator. When you prefix any expression with <span class=“text”>void</span>
, the result evaluates to <span class=“text”>undefined</span>
. So, using our correct method for checking <span class=“text”>undefined</span>
above you get this in the console:
true
Awesome!