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:
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
- Scotch.io: Logical Not Operator
- Stack Overflow: What is the not not operator
- Airbnb JavaScript Style Guide
- What is the purpose of new Boolean() in Javascript?
- Double Negation !!x
- You Don't Know JS: Coercion
- Originally published atย www.samanthaming.com
Thanks for reading โค
Say Hello! Instagram | Twitter | Blog | SamanthaMing.com
Top comments (12)
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.