32

How should I test if a variable is defined?

if //variable is defined
    //do this
else
    //do this
0

4 Answers 4

75
if (typeof variable !== 'undefined') {
  // ..
}
else
{
     // ..
}

find more explanation here:

JavaScript isset() equivalent

Sign up to request clarification or add additional context in comments.

3 Comments

Use !== for strict comparison and better performance.
@AmericanYak—in a typeof test the algorithm for resolving == and === is identical since both values have the same Type (string), so where does the better performance come from?
This fails when because typeof null is Object
8

Use the in operator.

'myVar' in window; // for global variables only

typeof checks will return true for a variable if,

  1. it hasn't been defined
  2. it has been defined and has the value undefined, or
  3. it has been defined but not initialized yet.

The following examples will illustrate the second and third point.

// defined, but not initialized
var myVar;
typeof myVar; // undefined

// defined, and initialized to undefined
var myVar = undefined;
typeof myVar; // undefined

5 Comments

You can use in window only in the special case of global variables as they are also made properties of the global object. Local variables have no such accssible variable object. Assuming that there is a window object might be reasonable for browsers but is not neccessarily true in general.
@RobG - it doesn't have to be window or the global object. Any object can be used here instead. You've raised a good point about variables defined locally not being accessible here. I'll be interested in finding out if there's a way to determine undefinedness for local variables based only on the first criteria I have.
If you are talking about variables and scope, then you can only distinguish between global variables (as they are properties of the global object) and the rest. In a nested function, it is impossible to tell if an identifier is a local or outer function variable because you can't access the related variable objects. Object property resolution is a different thing.
@RobG it's still the best answer because testing if the variable is merely equal to undefined doesn't mean anything other than it's undefined... but the variable might exists.
@LoïcFaure-Lacroix—there are no good answers here, it is impossible to tell if a local variable "exists" or not.
4

You simply check the type.

if(typeof yourVar !== "undefined"){
  alert("defined");
}
else{
  alert("undefined");
}

Comments

0

You can use something like this

if (typeof varname !== 'undefined') {
    // do this
} else {   
    // do that
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.