How to compare variables to undefined, if I don’t know whether they exist?
The best way is to check the type, because undefined
/null
/false
are a tricky thing in JS.
So:
if(typeof obj !== "undefined") {
// obj is a valid variable, do something here.
}
Note that typeof
always returns a string, and doesn't generate an error if the variable doesn't exist at all.
if (obj === undefined)
{
// Create obj
}
If you are doing extensive javascript programming you should get in the habit of using === and !== when you want to make a type specific check.
Also if you are going to be doing a fair amount of javascript, I suggest running code through JSLint http://www.jslint.com it might seem a bit draconian at first, but most of the things JSLint warns you about will eventually come back to bite you.
if (document.getElementById('theElement')) // do whatever after this
For undefined things that throw errors, test the property name of the parent object instead of just the variable name - so instead of:
if (blah) ...
do:
if (window.blah) ...