How to check if a variable is set?

Asked

Viewed 32,049 times

20

I tried to do it that way:

else if (vCodUG === undefined)

and made an error of:

Uncaught Referenceerror: vCodUG is not defined

erro no console

3 answers

36


Instead of comparing values

vCogUG == undefined

use the operator typeof:

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
}
  • 2

    The operator shall be used ===, because it is guaranteed that typeof will always return a string, making the code faster.

15

Use the operator typeof:

if (typeof nomeVar != 'undefined') {}
  • 5

    +1 for linking to documentation ;)

  • 2

    The operator shall be used !==, because it is guaranteed that typeof will always return a string, making the code faster.

14

The answers of Leofilipe and brandizzi 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 reachable in the scope, it will not be overwritten. Otherwise, you will have a variable with undefined value. In both cases, you can compare the way you were doing in your code. I prefer this form because we compare the value of the variable with undefined, instead of comparing its type with the literal string "undefined".

editing: Gibson called attention to the fact that, depending on the context, you will rather overwrite the variable. This occurs with closures (see his comment). If you are inside a closure or auto-invoked function, you better turn to typeof even.

  • That’s a great way! For me, every comparison with undefined should be so. The only problem is that the variable was not always declared. Which forces you to use the other methods. Apparently there are many Javascript programmers who like a little emotion: "does the variable exist? Doesn’t it? Scenes for the next chapter!" : P

  • If the variable has not been declared, you declare it just above where to check if it is undefined - This is what I propose here ;) Try it on the console: var foo = 1; var foo; foo === undefined;

  • 4

    The problem with this technique is if the variable is inherited from a broader lexical context (e.g., a closure). Example in jsFiddle. In this case it overrides yes the external context variable, and you end up with a different test result via typeof (example).

  • @mgibsonbr I didn’t know that. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.