[javascript] What is the !! (not not) operator in JavaScript?

I saw some code that seems to use an operator I don't recognize, in the form of two exclamation points, like so: !!. Can someone please tell me what this operator does?

The context in which I saw this was,

this.vertical = vertical !== undefined ? !!vertical : this.vertical;

This question is related to javascript operators

The answer is


!!x is shorthand for Boolean(x)

The first bang forces the js engine to run Boolean(x) but also has the side effect of inverting the value. So the second bang undoes the side effect.


This question has been answered quite thoroughly, but I'd like to add an answer that I hope is as simplified as possible, making the meaning of !! as simple to grasp as can be.

Because javascript has what are called "truthy" and "falsey" values, there are expressions that when evaluated in other expressions will result in a true or false condition, even though the value or expression being examined is not actually true or false.

For instance:

if (document.getElementById('myElement')) {
    // code block
}

If that element does in fact exist, the expression will evaluate as true, and the code block will be executed.

However:

if (document.getElementById('myElement') == true) {
    // code block
}

...will NOT result in a true condition, and the code block will not be executed, even if the element does exist.

Why? Because document.getElementById() is a "truthy" expression that will evaluate as true in this if() statement, but it is not an actual boolean value of true.

The double "not" in this case is quite simple. It is simply two nots back to back.

The first one simply "inverts" the truthy or falsey value, resulting in an actual boolean type, and then the second one "inverts" it back again to it's original state, but now in an actual boolean value. That way you have consistency:

if (!!document.getElementById('myElement')) {}

and

if (!!document.getElementById('myElement') == true) {}

will BOTH return true, as expected.


I suspect this is a leftover from C++ where people override the ! operator but not the bool operator.

So to get a negative(or positive) answer in that case you would first need to use the ! operator to get a boolean, but if you wanted to check the positive case would use !!.


It seems that the !! operator results in a double negation.

var foo = "Hello World!";

!foo // Result: false
!!foo // Result: true

!! is similar to using the Boolean constructor, or arguably more like the Boolean function.

_x000D_
_x000D_
console.log(Boolean(null)); // Preffered over the Boolean object_x000D_
_x000D_
console.log(new Boolean(null).valueOf()); // Not recommended for coverting non-boolean values_x000D_
_x000D_
console.log(!!null); // A hacky way to omit calling the Boolean function, but essentially does the same thing. _x000D_
_x000D_
_x000D_
// The context you saw earlier (your example)_x000D_
var vertical;_x000D_
_x000D_
function Example(vertical)_x000D_
{_x000D_
        this.vertical = vertical !== undefined ? !!vertical : _x000D_
        this.vertical; _x000D_
        // Let's break it down: If vertical is strictly not undefined, return the boolean value of vertical and set it to this.vertical. If not, don't set a value for this.vertical (just ignore it and set it back to what it was before; in this case, nothing).   _x000D_
_x000D_
        return this.vertical;_x000D_
}_x000D_
_x000D_
console.log( "\n---------------------" )_x000D_
_x000D_
// vertical is currently undefined_x000D_
_x000D_
console.log(new Example(vertical).vertical); // The falsey or truthy value of this.vertical_x000D_
console.log(!!new Example(vertical).vertical); // Coerced value of this.vertical_x000D_
_x000D_
vertical = 12.5; // set vertical to 12.5, a truthy value._x000D_
console.log(new Example(vertical).vertical); // The falsey or truthy value of this.vertical which happens to be true anyway_x000D_
console.log(!!new Example(vertical).vertical); // Coerced value of this.vertical_x000D_
_x000D_
vertical = -0; // set vertical to -0, a falsey value._x000D_
console.log(new Example(vertical).vertical); // The falsey or truthy value of this.vertical which happens to be false either way_x000D_
console.log(!!new Example(vertical).vertical); // Coerced value of this.vertical
_x000D_
_x000D_
_x000D_

Falsey values in javascript coerce to false, and truthy values coerce to true. Falsey and truthy values can also be used in if statements and will essentially "map" to their corresponding boolean value. However, you will probably not find yourself having to use proper boolean values often, as they mostly differ in output (return values).

Although this may seem similar to casting, realistically this is likely a mere coincidence and is not 'built' or purposely made for and like a boolean cast. So let's not call it that.


Why and how it works

To be concise, it looks something like this: ! ( !null ). Whereas, null is falsey, so !null would be true. Then !true would be false and it would essentially invert back to what it was before, except this time as a proper boolean value (or even vice versa with truthy values like {} or 1).


Going back to your example

Overall, the context that you saw simply adjusts this.vertical depending on whether or not vertical is defined, and if so; it will be set to the resulting boolean value of vertical, otherwise it will not change. In other words, if vertical is defined; this.vertical will be set to the boolean value of it, otherwise, it will stay the same. I guess that in itself is an example of how you would use !!, and what it does.


Vertical I/O Example

Run this example and fiddle around with the vertical value in the input. See what the result coerces to so that you can fully understand your context's code. In the input, enter any valid javascript value. Remember to include the quotations if you are testing out a string. Don't mind the CSS and HTML code too much, simply run this snippet and play around with it. However, you might want to take a look at the non-DOM-related javascript code though (the use of the Example constructor and the vertical variable).

_x000D_
_x000D_
var vertical = document.getElementById("vertical");_x000D_
var p = document.getElementById("result");_x000D_
_x000D_
function Example(vertical)_x000D_
{_x000D_
        this.vertical = vertical !== undefined ? !!vertical : _x000D_
        this.vertical;   _x000D_
_x000D_
        return this.vertical;_x000D_
}_x000D_
_x000D_
document.getElementById("run").onclick = function()_x000D_
{_x000D_
_x000D_
  p.innerHTML = !!( new Example(eval(vertical.value)).vertical );_x000D_
  _x000D_
}
_x000D_
input_x000D_
{_x000D_
  text-align: center;_x000D_
  width: 5em;_x000D_
} _x000D_
_x000D_
button _x000D_
{_x000D_
  margin: 15.5px;_x000D_
  width: 14em;_x000D_
  height: 3.4em;_x000D_
  color: blue;_x000D_
}_x000D_
_x000D_
var _x000D_
{_x000D_
  color: purple;_x000D_
}_x000D_
_x000D_
p {_x000D_
  margin: 15px;_x000D_
}_x000D_
_x000D_
span.comment {_x000D_
  color: brown;_x000D_
}
_x000D_
<!--Vertical I/O Example-->_x000D_
<h4>Vertical Example</h4>_x000D_
<code id="code"><var class="var">var</var> vertical = <input type="text" id="vertical" maxlength="9" />; <span class="comment">// enter any valid javascript value</span></code>_x000D_
<br />_x000D_
<button id="run">Run</button>_x000D_
<p id="result">...</p>
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
const foo = 'bar';
console.log(!!foo); // Boolean: true
_x000D_
_x000D_
_x000D_

! negates (inverts) a value AND always returns/ produces a boolean. So !'bar' would yield false (because 'bar' is truthy => negated + boolean = false). With the additional ! operator, the value is negated again, so false becomes true.


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.


!! 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.


Sometimes it is necessary to check whether we have a value in the function or not, and the amount itself is not important to us, but whether or not it matters. for example we want to check ,if user has major or not and we have a function just like:

hasMajor(){return this.major}//it return "(users major is)Science" 

but the answer is not important to us we just want to check it has a major or not and we need a boolean value(true or false) how we get it:

just like this:

hasMajor(){ return !(!this.major)}

or as the same

hasMajor(){return !!this.major)}

if this.major has a value then !this.major return false but because the value has exits and we need to return true we use ! twice to return the correct answer !(!this.major)


a = 1;
alert(!a) // -> false : a is not not defined
alert(!!a) // -> true : a is not not defined

For !a, it checks whether a is NOT defined, while !!a checks if the variable is defined.

!!a is the same as !(!a). If a is defined, a is true, !a is false, and !!a is true.


It's a double not operation. The first ! converts the value to boolean and inverts its logical value. The second ! inverts the logical value back.


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.
  • if (a & b) is a bitwise AND; if (a && b) is a logical AND. 2 & 5 is 0 (a false value); 2 && 5 is true.

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.


This is a really handy way to check for undefined, "undefined", null, "null", ""

if (!!var1 && !!var2 && !!var3 && !!var4 ){
   //... some code here
}

It's a horribly obscure way to do a type conversion.

! is NOT. So !true is false, and !false is true. !0 is true, and !1 is false.

So you're converting a value to a boolean, then inverting it, then inverting it again.

// Maximum Obscurity:
val.enabled = !!userId;

// Partial Obscurity:
val.enabled = (userId != 0) ? true : false;

// And finally, much easier to understand:
val.enabled = (userId != 0);

Brew some tea:

!! 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 not true (that's why !!true results in true)

  • The truth is that false is not not false (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).


Here are the three approaches:

// this won't tell us anything about HTML5 `<audio>` as a feature
var foo = function(tag, atr) { return document.createElement(tag)[atr]; }

// this won't return true if the feature is detected (although it works just fine)
var bar = function(tag, atr) { return !document.createElement(tag)[atr]; }

// this is the concise, feature-detecting solution we want
var baz = function(tag, atr) { return !!document.createElement(tag)[atr]; }

foo('audio', 'preload'); // returns "auto"
bar('audio', 'preload'); // returns false
baz('audio', 'preload'); // returns true

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:

// the native `hasOwnProperty` method
var qux = function(tag, atr) { return document.createElement(tag).hasOwnProperty(atr); }

// the `in` operator
var quux = function(tag, atr) { return atr in document.createElement(tag); }

qux('audio', 'preload');  // returns true
quux('audio', 'preload'); // returns true

We digress...

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.


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.

+-----------------------------------------------------------------------+
¦               Original                ¦    Equivalent     ¦  Result   ¦
¦---------------------------------------+-------------------+-----------¦
¦ if (-1 == true) console.log("spam")   ¦ if (-1 == 1)      ¦ undefined ¦
¦ if (-1 == false) console.log("spam")  ¦ if (-1 == 0)      ¦ undefined ¦
¦   Order doesn't matter...             ¦                   ¦           ¦
¦ if (true == -1) console.log("spam")   ¦ if (1 == -1)      ¦ undefined ¦
¦---------------------------------------+-------------------+-----------¦
¦ if (!!-1 == true) console.log("spam") ¦ if (true == true) ¦ spam      ¦ better
¦---------------------------------------+-------------------+-----------¦
¦ if (-1) console.log("spam")           ¦ if (truthy)       ¦ spam      ¦ still best
+-----------------------------------------------------------------------+

And things get even crazier depending on your engine. WScript, for instance, wins the prize.

function test()
{
    return (1 === 1);
}
WScript.echo(test());

Because of some historical Windows jive, that'll output -1 in a message box! Try it in a cmd.exe prompt and see! But WScript.echo(-1 == test()) still gives you 0, or WScript's false. Look away. It's hideous.

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?

if (!!customerInput.spouseName !== !!customerInput.spouseAge ) {
    errorObjects.spouse = "Please either enter a valid name AND age " 
        + "for your spouse or leave all spouse fields blank.";
}

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.


EDIT 24 Oct 2017, 6 Feb 19:

3rd party libraries that expect explicit Boolean values

Here's an interesting case... !! might be useful when 3rd party libs expect explicit Boolean values.

For instance, False in JSX (React) has a special meaning that's not triggered on simple falsiness. If you tried returning something like the following in your JSX, expecting an int in messageCount...

{messageCount && <div>You have messages!</div>}

... 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>}

  • I'm more comfortable handling falsiness myself with a ternary --
    {messageCount ? <div>You have messages!</div> : false}

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.


here is a piece of code from angular js

var requestAnimationFrame = $window.requestAnimationFrame ||
                                $window.webkitRequestAnimationFrame ||
                                $window.mozRequestAnimationFrame;

 var rafSupported = !!requestAnimationFrame;

their intention is to set rafSupported to true or false based on the availability of function in requestAnimationFrame

it can be achieved by checking in following way in general:

if(typeof  requestAnimationFrame === 'function')
rafSupported =true;
else
rafSupported =false;

the short way could be using !!

rafSupported = !!requestAnimationFrame ;

so if requestAnimationFrame was assigned a function then !requestAnimationFrame would be false and one more ! of it would be true

if requestAnimationFrame was assinged undefined then !requestAnimationFrame would be true and one more ! of it would be false


It forces all things to boolean.

For example:

console.log(undefined); // -> undefined
console.log(!undefined); // -> true
console.log(!!undefined); // -> false

console.log('abc'); // -> abc
console.log(!'abc'); // -> false
console.log(!!'abc'); // -> true

console.log(0 === false); // -> undefined
console.log(!0 === false); // -> false
console.log(!!0 === false); // -> true

! 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.

res = (1 && 2); // res is 2
res = (true && alert) // res is function alert()
res = ('foo' || alert) // res is 'foo'

In order to cast the condition to a true boolean literal we can use the double negation:

res = !!(1 && 2); // res is true
res = !!(true && alert) // res is true
res = !!('foo' || alert) // res is true

!!foo applies the unary not operator twice and is used to cast to boolean type similar to the use of unary plus +foo to cast to number and concatenating an empty string ''+foo to cast to string.

Instead of these hacks, you can also use the constructor functions corresponding to the primitive types (without using new) to explicitly cast values, ie

Boolean(foo) === !!foo
Number(foo)  === +foo
String(foo)  === ''+foo

!!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:

          !!false === false
           !!true === true

              !!0 === false
!!parseInt("foo") === false // NaN is falsy
              !!1 === true
             !!-1 === true  // -1 is truthy
          !!(1/0) === true  // Infinity is truthy

             !!"" === false // empty string is falsy
          !!"foo" === true  // non-empty string is truthy
        !!"false" === true  // ...even if it contains a falsy value

     !!window.foo === false // undefined is falsy
           !!null === false // null is falsy

             !!{} === true  // an (empty) object is truthy
             !![] === true  // an (empty) array is truthy; PHP programmers beware!

It's not a single operator, it's two. It's equivalent to the following and is a quick way to cast a value to boolean.

val.enabled = !(!enable);

It converts the suffix to a Boolean value.


Double boolean negation. Often used to check if value is not undefined.


It's just the logical NOT operator, twice - it's used to convert something to boolean, e.g.:

true === !!10

false === !!0

Tons of great answers here, but if you've read down this far, this helped me to 'get it'. Open the console on Chrome (etc), and start typing:

!(!(1))
!(!(0))
!(!('truthy')) 
!(!(null))
!(!(''))
!(!(undefined))
!(!(new Object())
!(!({}))
woo = 'hoo'
!(!(woo))
...etc, etc, until the light goes on ;)

Naturally, these are all the same as merely typing !!someThing, but the added parentheses might help make it more understandable.


Some operators in JavaScript perform implicit type conversions, and are sometimes used for type conversion.

The unary ! operator converts its operand to a boolean and negates it.

This fact lead to the following idiom that you can see in your source code:

!!x // Same as Boolean(x). Note double exclamation mark

Returns boolean value of a variable.

Instead, Boolean class can be used.

(please read code descriptions)

var X = "test"; // X value is "test" as a String value
var booleanX = !!X // booleanX is `true` as a Boolean value beacuse non-empty strings evaluates as `true` in boolean
var whatIsXValueInBoolean = Boolean(X) // whatIsXValueInBoolean is `true` again
console.log(Boolean(X) === !!X) // writes `true`

Namely, Boolean(X) = !!X in use.

Please check code snippet out below ?

_x000D_
_x000D_
let a = 0_x000D_
console.log("a: ", a) // writes a value in its kind_x000D_
console.log("!a: ", !a) // writes '0 is NOT true in boolean' value as boolean - So that's true.In boolean 0 means false and 1 means true._x000D_
console.log("!!a: ", !!a) // writes 0 value in boolean. 0 means false._x000D_
console.log("Boolean(a): ", Boolean(a)) // equals to `!!a`_x000D_
console.log("\n") // newline_x000D_
_x000D_
a = 1_x000D_
console.log("a: ", a)_x000D_
console.log("!a: ", !a)_x000D_
console.log("!!a: ", !!a) // writes 1 value in boolean_x000D_
console.log("\n") // newline_x000D_
_x000D_
a = ""_x000D_
console.log("a: ", a)_x000D_
console.log("!a: ", !a) // writes '"" is NOT true in boolean' value as boolean - So that's true.In boolean empty strings, null and undefined values mean false and if there is a string it means true._x000D_
console.log("!!a: ", !!a) // writes "" value in boolean_x000D_
console.log("\n") // newline_x000D_
_x000D_
a = "test"_x000D_
console.log("a: ", a) // writes a value in its kind_x000D_
console.log("!a: ", !a)_x000D_
console.log("!!a: ", !!a) // writes "test" value in boolean_x000D_
_x000D_
console.log("Boolean(a) === !!a: ", Boolean(a) === !!a) // writes true
_x000D_
_x000D_
_x000D_


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:

public isAuthenticated(): boolean {
   return !!this.getToken();
}

!! it's using NOT operation twice together, ! convert the value to a boolean and reverse it, here is a simple example to see how !! works:

At first, the place you have:

var zero = 0;

Then you do !0, it will be converted to boolean and be evaluated to true, because 0 is falsy, so you get the reversed value and converted to boolean, so it gets evaluated to true.

!zero; //true

but we don't want the reversed boolean version of the value, so we can reverse it again to get our result! That's why we use another !.

Basically, !! make us sure, the value we get is boolean, not falsy, truthy or string etc...

So it's like using Boolean function in javascript, but easy and shorter way to convert a value to boolean:

var zero = 0;
!!zero; //false

Use logical not operator two times
it means !true = false and !!true = true


The !! construct is a simple way of turning any JavaScript expression into its Boolean equivalent.

For example: !!"he shot me down" === true and !!0 === false.


To cast your JavaScript variables to boolean,

var firstname = "test";
//type of firstname is string
var firstNameNotEmpty = !!firstname;
//type of firstNameNotEmpty is boolean

javascript false for "",0,undefined and null

javascript is true for number other then zero,not empty strings,{},[] and new Date() so,

!!("test") /*is true*/
!!("") /*is false*/

It is important to remember the evaluations to true and false in JavaScript:

  • Everything with a "Value" is true (namely truthy), for example:

    • 101,
    • 3.1415,
    • -11,
    • "Lucky Brain",
    • new Object()
    • and, of course, true
  • Everything without a "Value" is false (namely falsy), for example:

    • 0,
    • -0,
    • "" (empty string),
    • undefined,
    • null,
    • NaN (not a number)
    • and, of course, false

Applying the "logical not" operator (!) evaluates the operand, converting it to boolean and then negating it. Applying it twice will negate the negation, effectively converting the value to boolean. Not applying the operator will just be a regular assignment of the exact value. Examples:

var value = 23; // number
var valueAsNegatedBoolean = !value; // boolean falsy (because 23 is truthy)
var valueAsBoolean = !!value; // boolean truthy
var copyOfValue = value; // number 23

var value2 = 0;
var value2AsNegatedBoolean = !value2; // boolean truthy (because 0 is falsy)
var value2AsBoolean = !!value2; // boolean falsy
var copyOfValue2 = value2; // number 0
  • value2 = value; assigns the exact object value even if it is not boolean hence value2 won't necessarily end up being boolean.
  • value2 = !!value; assigns a guaranteed boolean as the result of the double negation of the operand value and it is equivalent to the following but much shorter and readable:

_x000D_
_x000D_
if (value) {
  value2 = true;
} else {
  value2 = false;
}
_x000D_
_x000D_
_x000D_


I just wanted to add that

if(variableThing){
  // do something
}

is the same as

if(!!variableThing){
  // do something
}

But this can be an issue when something is undefined.

// a === undefined, b is an empty object (eg. b.asdf === undefined)
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" and we will continue down the so-called "&& chain" to the next value to the right.

P.S. Another way of doing the same thing is (b || {}).foo, because if b is undefined then b || {} will be {}, and you'll be accessing a value in an empty object (no error) instead of trying to access a value within "undefined" (causes an error). So, (b || {}).foo is the same as b && b.foo and ((b || {}).foo || {}).bar is the same as b && b.foo && b.foo.bar.