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

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.

Leave a Comment