Convert handle null variable using the length property in Javascript

1

I'm creating an application where a question has come up. In this application there may at some point be a variable where the value of it should be an empty string ( ) but, as I am forced to work with another team where I do not have full knowledge of the project, depending on the situation the return can be null .

Today, with all the knowledge I've gained, I can only think of using a multiple condition if this happens, as in the code below

var teste;
if(teste === null || teste.length == 0){
  return true;
}

Is there any way I can validate this teste === null in a more "beautiful" way?

NOTE : beautiful I say more readable.

    
asked by anonymous 06.08.2016 / 03:51

1 answer

2

Yes, there is a simpler and readable way (my opinion) to return this, just use the unary operator of negation (!). In JS there are values that are considered falsy , which during an operation that enforces coercion for Boolean, it considers this table of values falsy to consider the value as a false. Both empty string and null are values considered falsy , so denying these values results in true. To return, just do this:

return !teste;

You can see here the applicability of the truthy and falsy values of the language. If you want something more "complete", which explains a lot of details of how various JS operations work, including using JS itself as an example, you can see in the encyclopedia written by Crockford. Including there is a speaking part of the falsy values of the language. I think this Crockford wiki is fairly complete, I recommend.

    
06.08.2016 / 05:18