Just for the record, don't do what is quoted there. Do if(vertical !== undefined) this.vertical = Boolean(vertical); - it is much cleaner and clearer what is going on, requires no unnecessary assignment, is entirely standard, and is just as fast (on current FF and Chrome) jsperf.com/boolean-conversion-speed .
– Phil HFeb 12 '14 at 9:43

55

!! is not an operator. It's just the ! operator twice.
– VivekJul 16 '14 at 7:21

5

Just for the record, Boolean(5/0) is not the same as !!5/0
– schablukFeb 12 '15 at 9:45

48

@schabluk, for the record, order of operations is the reason !!5/0 produces Infinity rather than true, as produced by Boolean(5/0). !!5/0 is equivalent to (!!5)/0 -- a.k.a true/0 -- due to the ! operator having a higher precedence than the / operator. If you wanted to Booleanize 5/0 using a double-bang, you'd need to use !!(5/0).
– mattyMay 24 '15 at 13:47

It converts a nonboolean to an inverted boolean (for instance, !5 would be false, since 5 is a non-false value in JS), then boolean-inverts that so you get the original value as a boolean (so !!5 would be true).
– ChuckApr 24 '09 at 17:14

This is used to convert truthy values to boolean true, and falsy values too boolean false.
– thetoolmanJul 16 '12 at 3:53

9

@Micah Snyder be careful that in JavaScript it's better to use boolean primitives instead of creating objects that box booleans with new Boolean(). Here's an example to see the difference: jsfiddle.net/eekbu
– victorvartanFeb 3 '13 at 12:24

3

As far as I know, this bang-bang pattern is not useful inside a if(…_ statement; only in a return statement of a function that should return a boolean.
– rdsMar 26 '14 at 19:43

Is the "much easier to understand" variant really much easier to understand here? The check against 0 is not an actual check against 0, but a check against the somewhat weird list of values Javascript considers equal to 0. userId ? true : false makes more clear that there is conversion going on and handles the case where userId's value might have been explicitly set to undefined
– Ben RegenspanOct 13 '10 at 16:26

43

My brain doesn't have any problem decoding !!var into Boolean(var) .. and !! is faster (less instructions to process) and shorter than the alternatives.
– adamJLevOct 24 '10 at 23:36

!!expr returns a Boolean value (true or false) depending on the truthiness of the expression. It makes more sense when used on non-boolean types. Consider these examples, especially the 3rd example and onward:

new Boolean(false) is an object and an object is truthy even if it contains a falsy value!
– Salman ADec 18 '12 at 8:15

3

Yes I know, but consider the fact that most native constructors (String, Number, Date, etc) are meant to be callable as functions too, yet in this case the result is different!
– Camilo MartinDec 18 '12 at 8:25

!! is not an operator. It is the double-use of ! -- which is the logical "not" operator.

In theory:

! determines the "truth" of what a value is not:

The truth is that false is not true (that's why !false results
in true)

The truth is that true is not false (that's why !true results
in false)

!! determines the "truth" of what a value is not not:

The truth is that true is not nottrue (that's why !!true results in true)

The truth is that false is not notfalse (that's why !!false results in false)

What we wish to determine in the comparison is the "truth" about the value of a reference, not the value of the reference itself. There is a use-case where we might want to know the truth about a value, even if we expect the value to be false (or falsey), or if we expect the value not to be typeof boolean.

In practice:

Consider a concise function which detects feature functionality (and in this case, platform compatibility) by way of dynamic typing (aka "duck typing"). We want to write a function that returns true if a user's browser supports the HTML5 <audio> element, but we don't want the function to throw an error if <audio> is undefined; and we don't want to use try ... catch to handle any possible errors (because they're gross); and also we don't want to use a check inside the function that won't consistently reveal the truth about the feature (for example, document.createElement('audio') will still create an element called <audio> even if HTML5 <audio> is not supported).

Each function accepts an argument for a <tag> and an attribute to look for, but they each return different values based on what the comparisons determine.

But wait, there's more!

Some of you probably noticed that in this specific example, one could simply check for a property using the slightly more performant means of checking if the object in question has a property. There are two ways to do this:

However rare these situations may be, there may exist a few scenarios where the most concise, most performant, and thus most preferred means of getting true from a non-boolean, possibly undefined value is indeed by using !!. Hopefully this ridiculously clears it up.

totally awesome answer, but I fail to see the utility of the !! construct. Since an if() statement already casts the expression to boolean, explicitly casting the return value of a testing function to boolean is redundant - since "truthiness" === true as far as an if() statement goes anyway. Or am I missing a scenario where you NEED a truthy expression to actually be boolean true?
– Tom AugerApr 6 '16 at 13:27

1

@TomAuger if() statements do cast boolean against falsey values, but say you want to actually set a boolean flag on an object - it won't cast it like an if() statement does. For example object.hasTheThing = !!castTheReturnValToBoolNoMatterWhat() would set either true or false instead of the real return value. Another example is maybe all admins are id of 0 and non-admins are id 1 or higher. To get true if someone is not an admin you could do person.isNotAdmin = !!admin.id. Few use cases, but it's concise when there is.
– BennyMay 31 '18 at 15:41

!! converts the value to the right of it to its equivalent boolean value. (Think poor man's way of "type-casting"). Its intent is usually to convey to the reader that the code does not care what value is in the variable, but what it's "truth" value is.

Or in the case of a boolean value on the right, it does nothing.
– Daniel A. WhiteSep 10 '09 at 17:28

3

@Daniel: ! still flips the value to the right. In the case of a boolean the right-most ! negates the value, while the left-most ! negates it once again. Net effect is that there is no change, but most engines will generate op codes for the double negation.
– Crescent FreshSep 10 '09 at 17:34

But what is the point? If I do if(0){... Javascript already knows this is false. Why is it better to say if(!!0){...?
– CodyBugsteinMay 6 '16 at 23:37

the point is for variables that you might not know its contents; if it could be an integer or a string, an object or null, undefined, etc. This is an easy way to test existence.
– mix3dSep 22 '16 at 12:59

But then you can run into issues with instanceof. new Boolean(1) instanceof Object -> true !!1 instanceof Object -> false
– SeamusOct 7 '10 at 12:53

11

no, you can't: notice that the constructor functions are called without new - as explicitly mentioned in my answer
– ChristophOct 8 '10 at 9:46

2

fantastic! This is useful for a little hack when you need to evaluate strings with "0" as false instead of true. (i.e. when reading values from selects, because they are read as String). So, if you want to consider "0" as negative (Boolean false), asuming x="0" just do: x=!!+x; //false which is the same as Boolean(Number(x)) Number (or +x) converts the string "0" to 0, which DOES evaluate to false, and then Boolean (!!x) casts it to boolean directly. Easy peasy!
– DiegoDDJun 3 '13 at 18:13

So many answers doing half the work. Yes, !!X could be read as "the truthiness of X [represented as a boolean]". But !! isn't, practically speaking, so important for figuring out whether a single variable is (or even if many variables are) truthy or falsy. !!myVar === true is the same as just myVar. Comparing !!X to a "real" boolean isn't really useful.

What you gain with !! is the ability to check the truthiness of multiple variables against each other in a repeatable, standardized (and JSLint friendly) fashion.

Simply casting :(

That is...

0 === false is false.

!!0 === false is true.

The above's not so useful. if (!0) gives you the same results as if (!!0 === false). I can't think of a good case for casting a variable to boolean and then comparing to a "true" boolean.

See "== and !=" from JSLint's directions (note: Crockford is moving his site around a bit; that link is liable to die at some point) for a little on why:

The == and != operators do type coercion before comparing. This is bad because it causes ' \t\r\n' == 0 to be true. This can mask type errors. JSLint cannot reliably determine if == is being used correctly, so it is best to not use == and != at all and to always use the more reliable === and !== operators instead.

If you only care that a value is truthy or falsy, then use the short form. Instead of(foo != 0)

just say(foo)

and instead of(foo == 0)

say(!foo)

Note that there are some unintuitive cases where a boolean will be cast to a number (true is cast to 1 and false to 0) when comparing a boolean to a number. In this case, !! might be mentally useful. Though, again, these are cases where you're comparing a non-boolean to a hard-typed boolean, which is, imo, a serious mistake.if (-1) is still the way to go here.

Comparing truthiness :)

But what if I have two values I need to check for equal truthi/falsi-ness?

Pretend we have myVar1 = 0; and myVar2 = undefined;.

myVar1 === myVar2 is 0 === undefined and is obviously false.

!!myVar1 === !!myVar2 is !!0 === !!undefined and is true! Same truthiness! (In this case, both "have a truthiness of falsy".)

So the only place you'd really need to use "boolean-cast variables" would be if you had a situation where you're checking if both variables have the same truthiness, right? That is, use !! if you need to see if two vars are both truthy or both falsy (or not), that is, of equal (or not) truthiness.

I can't think of a great, non-contrived use case for that offhand. Maybe you have "linked" fields in a form?

So now if you have a truthy for both or a falsy for both spouse name and age, you can continue. Otherwise you've only got one field with a value (or a very early arranged marriage) and need to create an extra error on your errorObjects collection.

... you might be surprised to see React render a 0 when you have zero messages. You have to explicitly return false for JSX not to render. The above statement returns 0, which JSX happily renders, as it should. It can't tell you didn't have Count: {messageCount && <div>Get your count to zero!</div>} (or something less contrived).

One fix involves the bangbang, which coerces 0 into !!0, which is false:{!!messageCount && <div>You have messages!</div>}

JSX' docs suggest you be more explicit, write self-commenting code, and use a comparison to force to a Boolean.{messageCount > 0 && <div>You have messages!</div>}

Same deal in Typescript: If you have a function that returns a boolean (or you're assigning a value to a boolean variable), you [usually] can't return/assign a boolean-y value; it has to be a strongly typed boolean. This means, iff myObject is strongly typed, return !myObject; works for a function returning a boolean, but return myObject; doesn't. You have to return !!myObject to match Typescript's expectations.

The exception for Typescript? If myObject was an any, you're back in JavaScript's Wild West and can return it without !!, even if your return type is a boolean.

Keep in mind that these are JSX & Typescript conventions, not ones inherent to JavaScript.

But if you see strange 0s in your rendered JSX, think loose falsy management.

Good explanation. So would you say the !! is not strictly necessary in this Worker feature detection example? if (!!window.Worker)
– jk7May 6 '15 at 20:41

2

Nope, you wouldn't need it. Truthiness and true "externally" operate exactly the same in an if. I keep trying, but I can't think of a reason to prefer casting truthiness to a boolean value outside of the sort of convoluted "compare truthinesses" case, above, except for readability if you reuse the value later, as in the q library example. But even then, it's a information-lossy shortcut, and I'd argue you're better off evaluating truthiness each time.
– ruffinMay 6 '15 at 20:54

React is the main reason we've started using the !! pattern, but it happens to be a very convenient and repeatable thing. I only have to worry about the truthiness or falseyness of something, not what the underlying type is.
– Alexander PritchardJul 28 '18 at 23:02

Downvotes without comments make it difficult to address your concern! Let me know what looks bad, and I'll be happy to address it.
– ruffinJan 3 at 21:51

It simulates the behavior of the Boolean() casting function.
The first NOT returns a Boolean value no matter what operand it is given. The second NOT negates that Boolean value and so gives the true Boolean value of a variable. The end result is the same as using the Boolean() function on a value.

! is "boolean not", which essentially typecasts the value of "enable" to its boolean opposite. The second ! flips this value. So, !!enable means "not not enable," giving you the value of enable as a boolean.

I think worth mentioning is, that a condition combined with logical AND/OR will not return a boolean value but last success or first fail in case of && and
first success or last fail in case of || of condition chain.

The if and while statements and the ? operator use truth values to determine which branch of code to run. For example, zero and NaN numbers and the empty string are false, but other numbers and strings are true. Objects are true, but the undefined value and null are both false.

The double negation operator !! calculates the truth value of a value. It's actually two operators, where !!x means !(!x), and behaves as follows:

If x is a false value, !x is true, and !!x is false.

If x is a true value, !x is false, and !!x is true.

When used at the top level of a Boolean context (if, while, or ?), the !! operator is behaviorally a no-op. For example, if (x) and if (!!x) mean the same thing.

Practical uses

However it has several practical uses.

One use is to lossily compress an object to its truth value, so that your code isn't holding a reference to a big object and keeping it alive. Assigning !!some_big_object to a variable instead of some_big_object lets go of it for the garbage collector. This is useful for cases that produce either an object or a false value such as null or the undefined value, such as browser feature detection.

Another use, which I mentioned in an answer about C's corresponding !! operator, is with "lint" tools that look for common typos and print diagnostics. For example, in both C and JavaScript, a few common typos for Boolean operations produce other behaviors whose output isn't quite as Boolean:

if (a = b) is assignment followed by use of the truth value of b; if (a == b) is an equality comparison.

The !! operator reassures the lint tool that what you wrote is what you meant: do this operation, then take the truth value of the result.

A third use is to produce logical XOR and logical XNOR. In both C and JavaScript, a && b performs a logical AND (true if both sides are true), and a & b performs a bitwise AND. a || b performs a logical OR (true if at least one are true), and a | b performs a bitwise OR. There's a bitwise XOR (exclusive OR) as a ^ b, but there's no built-in operator for logical XOR (true if exactly one side is true). You might, for example, want to allow the user to enter text in exactly one of two fields. What you can do is convert each to a truth value and compare them: !!x !== !!y.

// a is undefined, b is empty object.
var a, b = {};
// Both of these give error a.foo is not defined etc.
// you'd see the same behavior for !!a.foo and !!b.foo.bar
a.foo
b.foo.bar
// This works -- these return undefined
a && a.foo
b.foo && b.foo.bar
b && b.foo && b.foo.bar

The trick here is the chain of &&s will return the first falsey value it finds -- and this can be fed to an if statement etc. So if b.foo is undefined, it will return undefined and skip the b.foo.bar statement, and we get no error.

The above return undefined but if you have an empty string, false, null, 0, undefined those values will return and soon as we encounter them in the chain -- [] and {} are both truthy.

After seeing all these great answers, I would like to add another reason for using !!. Currenty I'm working in Angular 2-4 (TypeScript) and I want to return a boolean as false when my user is not authenticated. If he isn't authenticated, the token-string would be null or "". I can do this by using the next block of code: