Testing for undefined variables in JavaScript
There are all manner of tests for undefined in JavaScript it seems.
if typeof(foo) == 'undefined' or
foo === undefined. So when should you use which?
The following shell example explains:
deryck@domino:~$ js js> foo === undefined; typein:10: ReferenceError: foo is not defined js> typeof(foo) == 'undefined'; true js> var foo; js> foo === undefined; true
In browser, there is also the window.foo === undefined construction,
instead of typeof(foo), but the latter seems clearer in code to me.
Posted by deryck on July 23, 2009

