I tried to do it this way:
else if (vCodUG === undefined)
and gave error of:
Uncaught ReferenceError: vCodUG is not defined
I tried to do it this way:
else if (vCodUG === undefined)
and gave error of:
Uncaught ReferenceError: vCodUG is not defined
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
}
Use the typeof
operator. :
if (typeof nomeVar != 'undefined') {}
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.