DEV Community

Cover image for 2 Ways to Convert Values to Boolean in JavaScript

2 Ways to Convert Values to Boolean in JavaScript

Samantha Ming on February 20, 2020

My favorite is using !!. Itโ€™s also the recommended method by Airbnb's JavaScript style guide ๐Ÿ‘ Boolean(value); !!value; Convert V...
Collapse
 
moopet profile image
Ben Sinclair

When it's only an expression, it can stay an expression:

// better (works explicitly):
if (!!a) {
}

is not better than this:

if (a) {
}
Collapse
 
samanthaming profile image
Samantha Ming

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 ๐Ÿ˜‚

Collapse
 
moopet profile image
Ben Sinclair

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.

Collapse
 
delta456 profile image
Swastik Baranwal

Wow I never knew this. Looks very stupid especially !!

Collapse
 
mzaini30 profile image
Zen

I didn't use !! yet. I usually use like this:

something ? /* if true */ : /* if false */

Not this:

!!something ? /* if true */ : /* if false */
Collapse
 
samanthaming profile image
Samantha Ming • Edited

May I add something, if you don't mind ๐Ÿ˜Š

something ? /* if truthy */ : /* if falsy */

Because doing something like this something will capture all truthy/falsy value and not just true/false. I've made that mistake in past, so I just want to include this friendly reminder to be mindful of ๐Ÿ‘

Collapse
 
mzaini30 profile image
Zen

Oh thanks ๐Ÿ˜‚

Collapse
 
mzaini30 profile image
Zen

I just found out that truth / falsy is different from true / false. Very cool, Javascript

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

Well thatโ€™s neat! I didnโ€™t realize that an expression shorthand existed for conversion to Boolean. Thanks for posting!

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ

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

Collapse
 
samanthaming profile image
Samantha Ming

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 ๐Ÿ˜‰

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

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.