Ok, here is my question: in javascript you can declare a variable and if it's undefined you can apply variable == undefined, I know that but how can you compare a value that you dont know yet if it's in the cpu memory. I have a class which is created when the user clicks a button. Before this the class is undefined, it doesn't exist anywhere so how can I compare it? without using try{}catch(e){} is there a way????
+1
A:
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) ...
Delan Azabani
2010-05-06 06:37:27
no I don't think because you get a null when you compare a xhtml element with javascript always you can do element == null or what you do... I mean when you compara VARIABLE that is not in the cpu memory... for examplefunction(){ if(variableNeverDeclared == undefined) //do something //this is gonna throw an erro cause variableNeverDeclared does not exist}
nahum
2010-05-06 06:46:48
I been doing try catch but I dont think is the best option
nahum
2010-05-06 06:47:40
Updated the answer to accurately answer your question.
Delan Azabani
2010-05-06 07:07:25
+6
A:
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.
Makram Saleh
2010-05-06 07:00:00