Javascript: Testing For Undefined

While working on a project, I wanted to test whether a variable was undefined in Javascript. Because Firebug displayed ‘undefined’ in the console, I assumed that I could treat it as a string.

?View Code JAVASCRIPT
if (variable == 'undefined') {
// do something
}

Now I knew that this wouldn’t work, but I tried it anyway. ‘undefined’ an object, not a string, so I could not treat it as a string.

After a minute of searching, I found the undefined solution:

?View Code JAVASCRIPT
if (typeof(variable) == 'undefined') {
// do something
}

Using the typeof operator, Javascript is able to determine whether a variable/object is ‘undefined’.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks