Javascript: Testing For Undefined
Tuesday, January 12th, 2010While 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.
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:
if (typeof(variable) == 'undefined') { // do something } |
Using the typeof operator, Javascript is able to determine whether a variable/object is ‘undefined’.


