How to compare variables to undefined, if I don’t know whether they exist?

ncubica picture ncubica · May 6, 2010 · Viewed 132.4k times · Source

In JavaScript you can declare a variable and if it’s undefined, you can check variable == undefined; I know that, but how can you compare a value that you don’t know yet if it’s in memory?

For example, I have a class which is created when the user clicks a button. Before this, the class is undefined — it doesn’t exist anywhere; how can I compare it?

Is there a way without using trycatch?

Answer

Makram Saleh picture Makram Saleh · May 6, 2010

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.