The simplest way to check whether the variable has been defined takes into account that js considers the value undefined
as false
in one condition. However the values null
and 0
are also considered as false
.
if (onlyteste) {
// existe
}
A more correct way, taking into account that only passes when the variable has not actually been defined:
if (typeof onlyteste != 'undefined') {
// existe
}
Going a little further, typescript generates the following code:
if (onlyteste !== void 0) {
// existe
}
Edit
A detail in your question that I didn’t notice when preparing the answer: if the variable is not yet declared, only the second solution I have put forward will work. Use any of the solutions (except the first) to check if the variable was 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
}
}
I don’t understand why -1 is still wrong, see https://jsfiddle.net/tt7rezseconsole/
– Elaine
@Elaine Look what I used
typeof onlyteste != 'undefined'
and notonlyteste != undefined
. The second approach may generate unexpected results in specific cases.– Oeslei
It worked! Thank you!
– Elaine