This condition returns a boolean when checking for a falsy, but it returns a string when checking for a truthy value. How can I get it to work?

327 views Asked by At

I get a boolean return when checking for a falsy value, but not a boolean when checking for a truthy value... I am just getting a string instead.

This works.

const isFalse = !values.firstName && !values.lastName && !values.email;

But this doesn't, as I get returned a string only.

const isValid = values.firstName && values.lastName && values.email;

Although, I can achieve the desired result with the following... It doesn't seem the best way forward.

const isValid = values.firstName && values.lastName && values.email ? true : false;

How would I be able to check the string for a truthy value and get boolean as a result (instead of a string)?

2

There are 2 answers

4
Grateful On

Wow, that was quick. I found out that you can do a double negative to achieve the same result and get it to work!! (pun intended)

const isValid = !!(values.firstName && values.lastName && values.email);
7
xurei On

Well, Javascript can be weird sometimes... I don't know exactly why it happens, but I can tell you how to get a boolean value:

const isValid = !!values.firstName && !!values.lastName && !!values.email;

BONUS: for a good laugh, check this: https://www.destroyallsoftware.com/talks/wat