How to check if a variable is defined?

17

I tried to do it this way:

else if (vCodUG === undefined)

and gave error of:

  

Uncaught ReferenceError: vCodUG is not defined

    
asked by anonymous 05.06.2014 / 16:24

3 answers

25

Instead of comparing values

vCogUG == undefined

use the typeof operator:

typeof vCogUG == "undefined"

Example :

if (typeof vCogUG == "undefined") {
    alert("vCogUG é undefined");  // Será mostrado
} else {
    alert("O valor de vCogUG é " + vCogUG); // Não será mostrado
}

var vCogUG = 3;

if (typeof vCogUG == "undefined") {
    alert("vCogUG é undefined"); // Não será mostrado
} else {
    alert("O valor de vCogUG é " + vCogUG); // Será mostrado
}
    
05.06.2014 / 16:28
12

Use the typeof operator. :

if (typeof nomeVar != 'undefined') {}
    
05.06.2014 / 16:29
12

LeoFilipe and brandizzi answers are correct.

There is, however, an alternative you can use for a similar check:

var vCogUG;
vCogUG === undefined;

If the variable vCogUG already exists and is accessible in scope, it will not be overwritten . Otherwise, you'll have a variable of undefined value. In either case, you can compare the way you were doing in your code. I prefer this form because we then compare the value of the variable with undefined , instead of comparing its type with the literal string "undefined" .

editing: Gibson has pointed out that, depending on the context, you will override the variable. This occurs with closures (see his comment). If it is within a closure or a self-invoked function, it is better to use% s of% itself.

    
05.06.2014 / 16:41