Qual é a forma mais apropriada de testar se uma variável não está definida no JavaScript? I'já vi várias maneiras possíveis:
if (window.myVariable)
Ou
if (typeof(myVariable) != "undefined")
Ou
if (myVariable) //This throws an error if undefined. Should this be in Try/Catch?
Você precisa utilizar o tipo de
.
if (typeof something != "undefined") {
// ...
}
Se for indefinida, não será igual a uma string que contém os caracteres "undefined" como a string não é indefinida.
Você pode verificar o tipo da variável:
if (typeof(something) != "undefined") ...
Às vezes você não'nem mesmo tem que verificar o tipo. Se o valor da variável pode't avaliar para falso quando ela's é definida (por exemplo se ela's é uma função), então você pode apenas avaliar a variável. Exemplo:
if (something) {
something(param);
}