How to avoid error when variable not declared

Asked

Viewed 475 times

1

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

How can I detect that it was not set and give a return; Why does the coode stop? I tried:

if(!onlytest) {
return;
}

but it does not work it says it was not set, how to avoid this error and give the Return when it is not set?

2 answers

1


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/

  • 2

    @Elaine Look what I used typeof onlyteste != 'undefined' and not onlyteste != undefined. The second approach may generate unexpected results in specific cases.

  • It worked! Thank you!

0

You can check before if the variable has been set. Thus:

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

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

if(onlytest === undefined){
   return false;
}
  • is still in error, see https://jsfiddle.net/tt7rezseconsole/

Browser other questions tagged

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