views:

110

answers:

3

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
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
I been doing try catch but I dont think is the best option
nahum
Updated the answer to accurately answer your question.
Delan Azabani
A: 
if (!obj) {
    // object (not class!) doesn't exist yet
}
else ...
Thevs
+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
ooook .. that's cool thanks =)
nahum