Convert treat null variable using the length property in Javascript

Asked

Viewed 44 times

1

I’m creating an app where I have a question. In this application there may be at some point a variable where its value should be an empty string ("") but, as I am obliged 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 have achieved, I can only think of using a multiple condition if it occurs, 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: pretty I say more readable.

1 answer

2


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

return !teste;

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

  • excellent! thank you very much!

Browser other questions tagged

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