Comparison in JavaScript

4

Well, I want to know if my comparison can be improved, I want to leave the code shorter.

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()

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

    
asked by anonymous 25.03.2018 / 05:24

3 answers

6

You can only do:

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

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

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

Test:

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
    
25.03.2018 / 05:33
5

You can also do 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);
    
25.03.2018 / 05:37
5

The other answers suggest a check for values falsey , which excludes more than your condition.

Without changing the direction 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 intent with a != "" is to exclude only empty strings, use the strict equality comparator === :

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

Otherwise, it will also prohibit values that return '' when converted to strings - such as empty arrays, for example.     

26.03.2018 / 05:59