My favorite is using !!. Itโs also the recommended method by Airbnb's JavaScript style guide ๐
Boolean(value);
!!value;
Convert V...
For further actions, you may consider blocking this person and/or reporting abuse
When it's only an expression, it can stay an expression:
is not better than this:
Your latter example would be the "implicit" coercion. Under the hood, I believe JavaScript is doing something similar to the
!!
way, right? So the result would be the same . I don't recall completely unfortunately ...but if you know, let me know and save me a trip to google ๐It's not really coercion, or I don't think it goes that far. It's just that
!!
is saying "make this a boolean if it's "truthy" and you can just use the "is it truthy" instead.Casting to boolean is only useful if you're going to do something like supply it to an API that expects a boolean.
Wow I never knew this. Looks very stupid especially
!!
I didn't use
!!
yet. I usually use like this:Not this:
May I add something, if you don't mind ๐
Because doing something like this
something
will capture all truthy/falsy value and not justtrue
/false
. I've made that mistake in past, so I just want to include this friendly reminder to be mindful of ๐Oh thanks ๐
I just found out that truth / falsy is different from true / false. Very cool, Javascript
Kenal JavaScript: Truthy dan Falsy - Jundi Alwan - Medium
Jundi Alwan ใป ใป 5 min read
Medium
Well thatโs neat! I didnโt realize that an expression shorthand existed for conversion to Boolean. Thanks for posting!
It isn't a shorthand, it is part of how the language works. An 'if' statement expects a boolean, so it will coerce whatever you give it to a boolean - no need to do the conversion yourself
Exactly Jon! I remember being told auto coercion is this scary beast. But then if you understand it, you can make the beast work for you ๐. It's just another thing JavaScript tries to help. And if you know what it's trying to do, why not let it ๐
Yes, after thinking about it, I realized that youโre coercing to Boolean and negating, then undoing negation. My โshorthandโ remark was meant in the sense of fewer characters to type.