How to avoid error when variable is not declared

1

I have a function that defines onlytest after the first execution of another script, but at the first run it was not defined.

How can I detect that it has not been set and give return; so the code stops? I've tried:

if(!onlytest) {
return;
}

but it does not work, it says it has not been defined, how to avoid this error and give the return when it is not defined?

    
asked by anonymous 14.07.2015 / 18:12

2 answers

1

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
    }
}
    
14.07.2015 / 18:41
0

You can first check whether the variable has been defined. So:

if(onlytest !== undefined){
   //Ações aqui
}

In this way, you can know whether or not the variable has been set. And here's something similar to what you wanted to do:

if(onlytest === undefined){
   return false;
}
    
14.07.2015 / 18:38