DEV Community

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

Posted on • Originally published at samanthaming.com

2 Ways to Convert Values to Boolean in JavaScript

Alt Text

My favorite is using !!. Itโ€™s also the recommended method by Airbnb's JavaScript style guide ๐Ÿ‘

Boolean(value);

!!value;

Convert Values to Boolean

String

const string = 'string';

!!string; // true
Boolean(string); // true

Number

const number = 100;

!!number; // true
Boolean(number); // true

Falsy Values

In JavaScript, there are 6 falsy values. If you convert any of these to a boolean, it will return false.

false
undefined
null
NaN
0
"" (empty string)

Anything not on the falsy list, will return true ๐Ÿ‘

More information on this, you can read my Code Notes on Falsy Values

Examples

Applying !! on falsy values

!!false; // false
!!undefined; // false
!!null; // false
!!NaN; // false
!!0; // false
!!''; // false

Applying Boolean on falsy values

Boolean(false); // false
Boolean(undefined); // false
Boolean(null); // false
Boolean(NaN); // false
Boolean(0); // false
Boolean(''); // false

How the !! works

The first ! coerce the value to a boolean and inverse it. In this case, !value will return false. So to reverse it back to true, we put another ! on it. Hence the double use !!.

const value = 'string';

!value; // false

!!value; // true

Watch out for 'false'

const value = 'false';

!!value; // true
Boolean(value); // true

Notice the "false" is between quotes '. Although it says false, it's actually a string. I know most of you won't fall for this, but if you're like me, you might just want to be alert for these funny mind tricks people might be playing on you ๐Ÿ˜‚

Community Input

@tassoevan: I enjoy filtering falsy values from arrays like this: myArray.filter(Boolean)

@fleonus: I like !+! just to be cool and throw people off :P

Speed Test

Here's a test that I found:

boolean vs !!

Looks like the !! is a bit faster than Boolean

Which one to use?

I've gotten a lot of comments on this post. Some people prefer the Boolean because it's more explicit.

But, Kyle Simpson from You Don't Know JS, mentioned that both are explicit.

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

// also great (works explicitly):
if (Boolean(a)) {
}

Kyle Simpson: YDKJS - Coercion

I don't think I have a great answer for you. You will know your team way better I do. I will continue to use !! in my own personal projects, cause it's less typing and I understand this syntax. But if I was on a team, I might choose Boolean because I think most developers would understand that better. No matter which one you choose, the most important thing is to be consistent. Don't flip-flop between the two in your code base. Pick one and stick with it ๐Ÿ’ช

Aludding to an awesome comment I got:

@patrick_developer: I say one should understand both just in case one is presented with different code bases that use each one. Knowledge is power.

In other words, one is not better than the other. This one I'd argue is more of a preference. So you can't go wrong. But don't deprive yourself from understanding both. Like Patrick said, "Knowledge is power" ๐Ÿ’ช

Avoid new Boolean

Use Primitives instead of Object Types

var str = 'str';

// Avoid
typeof new Boolean(str); // object

// Preferred
typeof Boolean(str); // boolean
typeof !!str; // boolean

CJ J.: It's worth noting that new Boolean isn't a boolean but rather an instance of Boolean. Primitives are cheaper and should be preferred over the object type.

CJ J.: new Boolean(str) returns an object type. Boolean(str) just returns a primitive boolean. I would suspect Boolean(str) is faster then !!str because it's only one operation, but it's also entirely possible that browsers implement an optimization such that when they see !! they know to directly cast the argument to a boolean primitive (instead of actually doing NOT() twice in a row).

CJ J.: Primitives are cheap because they're immutable so you can share references and not have to hold any state on the instance. It's just true or false. But new Boolean(str) is an object. It has it's own unique memory address and it can hold internal state that is unique to it. This means it can't just hold a reference to an immutable singleton instance. Every call to new Boolean(str) instantiates an entire new Boolean() object.

Thanks: CJ J.

Remove empty strings with Boolean Constructor

CJ J.: This is the classic example. If you get a list of string values separated by commas and you want to filter out the empty strings, you can pass the Boolean constructor function into Array.prototype.filter and it will automatically strip out the zero-length strings leaving an array of only valid strings.

var str = 'some,list,,of,values';
var arr = str.split(',');

arr; // [ 'some', 'list', '', 'of', 'values' ]

arr.filter(Boolean); // [ 'some', 'list', 'of', 'values' ]

Thanks: CJ J.

Resources


Thanks for reading โค
Say Hello! Instagram | Twitter | Blog | SamanthaMing.com

Top comments (12)

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.