The simplest way to check if the variable was defined takes into account that js considers the value undefined
as false
in a condition. However, the null
and 0
values are also considered as false
.
if (onlyteste) {
// existe
}
A more correct way, given that it only passes when the variable has not really been defined:
if (typeof onlyteste != 'undefined') {
// existe
}
Going even further, typescript generates the following code:
if (onlyteste !== void 0) {
// existe
}
Edit
A detail in your question that I did not realize when I compiled the answer: If the variable is not yet declared , only the second solution I submitted will work. Use any of the solutions (with the exception of the first) to check if the variable has been initialized / set.
function minhaFuncao () {
if (1 == 0) {
var onlyteste = 'ok';
}
if (typeof onlyteste == 'undefined') {
// variável não existe
}
}
function minhaFuncao () {
var onlyteste;
if (1 == 0) {
onlyteste = 'ok';
}
if (onlyteste) {
// não inicializada
}
if (typeof onlyteste == 'undefined') {
// não inicializada
}
if (onlyteste === void 0) {
// não inicializada
}
}