Javascript comparison

Asked

Viewed 86 times

3

well I want to know if my comparison has how to be improved, I want to make the code shorter (dry)

const teste = function(a){
   if(a != null && a != undefined && a != ""){
        console.log('e diferente')
    }else{
        console.log(`o valor que vc passou e ${a}`)
    }
}

teste()

About the part if(a != null && a != undefined && a != ""), how can I make it shorter?

3 answers

5

Can only do:

if(a){
   ...
}else{
   ...
}

a would have to be different from null, Undefined and emptiness. Exactly the 3 conditions you put in your code, adding that also can’t be the number 0 (teste(0)). If you want to allow 0, would have to do:

if(a || a === 0){

Testing:

const teste = function(a){
   if(a){
        console.log('e diferente')
    }else{
        console.log(`o valor que vc passou e ${a}`)
    }
}

teste() // else
teste(' ') // if
teste(0) // else
teste('0') // if
teste('') // else

5

You can do it like this:

const teste = function(a) { a ? console.log(`O valor que vc passou é ${a}`) : console.log('Nenhum valor informado') };

teste('Teste');
teste('');
teste(null);
teste(undefined);

Or use Arrow Function

const teste = a => a ? console.log(`O valor que vc passou é ${a}`) : console.log('Nenhum valor informado');

teste('Teste');
teste('');
teste(null);
teste(undefined);

  • the code could become even more readable, because an Arrow function with only one parameter does not need to ( ), would be... const test = a => a ?...

  • Yes, but considering your question: the part if(a != null && a != Undefined && a != "") how can I make it shorter ? ... That wasn’t the focus when answering.

  • Arrow funtion are not compatible with a pair browsers

4

Other responses suggest a value check falsey, which excludes more than its condition.

Without changing the meaning of your original code, you can simply remove the first or second condition. They are identical because you are not using comparison of strict equality. So if the purpose of the code is to get smaller, you can simply use:

if (a != null && a != "")

If your intention with a != "" is to exclude only empty strings, use the strict equality comparator ===:

if (a != null && a !== "")

Otherwise it will also prohibit returning values '' when converts for strings - as empty arrays, for example.

Browser other questions tagged

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