Undefined

Nouveau Variation on Flickr

(Photo: Nouveau Variation by Syntopia)

I find the undefined keyword and identity operators (=== and !==) in JavaScript pretty useful.  For example if I am parsing a JSON input and I am not sure if something is there or not I test it like this.

if (root.Foo === undefined)

If I want to test if something is defined I do it like this.

if (root.Bar !== undefined)

saladwithsteve explains it well in his JavaScript undefined vs. null post.

Update 12-14-2009: Unfortunately the above method did not work for testing a variable directly.  I ended up following the advice of this post, Javascript IsDefined Function.  To test if a variable is defined I now do this.

if (typeof(foo) != "undefined")

Leave a Reply

Your email address will not be published. Required fields are marked *