ncubica ncubica - 2 months ago 7
Javascript Question

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

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
try
catch
?

Answer

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.