Hexagon Theory
Hexagon Theory

Reputation: 44823

What does the !! (double exclamation mark) operator do in JavaScript?

I saw this code:

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

It seems to be using !! as an operator, which I don't recognize. What does it do?

Upvotes: 4203

Views: 965583

Answers (30)

Salman Arshad
Salman Arshad

Reputation: 272316

!!expr (two ! operators followed by an expression) returns the primitive true or false depending on the truthiness of the expression.

It makes sense when used on non-boolean expressions. Some examples:

Note: the Boolean function produces the exact same results, and it is more readable.

          !!false // false
           !!true // true

              !!0 // false
!!parseInt("foo") // false — NaN is falsy
              !!1 // true
             !!-1 // true  — negative number 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 value is falsy
      !!undefined // false — undefined primitive is falsy
           !!null // false — null is falsy

             !!{} // true  — an (empty) object is truthy
             !![] // true  — an (empty) array is truthy

Upvotes: 603

Gad Iradufasha
Gad Iradufasha

Reputation: 151

Say Less It simply means: Not Not

console.log(!true) // false
console.log(!!true) // true

Upvotes: -1

Mohit Singh
Mohit Singh

Reputation: 591

First of all, it is worth mentioning that the double-negation is not a JavaScript operator but simply two negations in a sequence.

Let’s try to break down a simple example.

!!myVariable

In other words, the double-NOT converts myVariablein our example to a boolean. The value of the resulting boolean depends on the original value of myVariable.

But what if the initial value is not a boolean true or false?

We need to introduce the concept of truthy and falsy.

Truthy and Falsy

A falsy value is

  • null
  • NaN
  • 0
  • empty string ("" or '' or ``)
  • undefined

JavaScript interprets these values as false. Check the link for a complete list of falsy values.

Whatever is not falsy is interpreted as true.

Enter !!

Now we know that the NOT operator in front of a variable, like !myVariable, converts myVariable to a boolean based on the original value of myVariable.

JavaScript follows the following steps when interpreting !myVariable:

  1. Converts myVariable to a boolean.
  2. Apply ! in front of the resulting boolean.
  3. Convert it to the opposite.

What if we add another NOT operator? In brief, it converts it again!

Following the steps above, we repeat steps 2 and 3!

  1. Converts myVariable to a boolean.
  2. Apply ! in front of the resulting boolean.
  3. Convert it to the opposite.
  4. Apply ! in front of the resulting boolean.
  5. Convert it to the opposite.

For this reason, !! is often used to return the boolean value of truthy, falsy, or expressions.

It is like saying: “Give me the boolean value of this expression”, whatever the expression is. It could be a function, the result of a function, an object, etc.

if([]) {
  console.log("true");
} else {
  console.log("false");
}
true
undefined
if(![]) {
  console.log("true");
} else {
  console.log("false");
}
false
undefined
if(!![]) {
  console.log("true");
} else {
  console.log("false");
}
true
undefined

Upvotes: 1

stevehipwell
stevehipwell

Reputation: 57538

It converts Object to boolean. If it was falsy (e.g., 0, null, undefined, etc.), it would be false, otherwise, true.

!object  // Inverted Boolean
!!object // Noninverted Boolean, so true Boolean representation

So !! is not an operator; it's just the ! operator twice.

It is generally simpler to do:

Boolean(object) // Boolean

Real World Example "Test IE version":

const isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // Returns true or false

If you ⇒

console.log(navigator.userAgent.match(/MSIE 8.0/));
// Returns either an Array or null

But if you ⇒

console.log(!!navigator.userAgent.match(/MSIE 8.0/));
// Returns either true or false

Upvotes: 3735

Tom Ritter
Tom Ritter

Reputation: 101400

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

! means 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, inverting it, and 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);

    // Or just
    val.enabled = Boolean(userId);

Note: the middle two expressions aren't exactly equivalent to the first expression when it comes to some edge cases (when userId is [], for example) due to the way the != operator works and what values are considered truthy.

Upvotes: 1033

ruffin
ruffin

Reputation: 17473

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.

The only thing 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: site has changed; this is an archived copy) 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, in my opinion, a serious mistake. if (-1) is still the way to go here.

Original Equivalent Result Notes
if (-1 == true) console.log("spam") if (-1 == 1) undefined
if (-1 == false) console.log("spam") if (-1 == 0) undefined
if (true == -1) console.log("spam") if (1 == -1) undefined Order doesn't
matter...
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 truthiness/falsiness?

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

Though even in this case, the !! really is superfluous. One ! was enough to cast to a Boolean, and you're just checking equality.


EDIT 24 Oct 2017, 6 Feb 19:

Third-party libraries that expect explicit Boolean values

Here's an interesting case... !! might be useful when third-party libraries expect explicit Boolean values.

React

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

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

  • JSX' documentation suggests 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}

TypeScript

The 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 (or cast to the proper Boolean another way) 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 and TypeScript conventions, not ones inherent to JavaScript.

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

Upvotes: 95

Twitter khuong291
Twitter khuong291

Reputation: 11702

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);   // -> false
console.log(!0 === false);  // -> false
console.log(!!0 === false); // -> true

Upvotes: 20

Benny Schmidt
Benny Schmidt

Reputation: 3394

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.

Upvotes: 218

Lakmal
Lakmal

Reputation: 928

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 than zero, not empty strings, {}, [] and new Date() so,

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

Upvotes: 3

KWallace
KWallace

Reputation: 632

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 "falsy" 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 falsy value, resulting in an actual Boolean type, and then the second one "inverts" it back again to its 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.

Upvotes: 15

efkan
efkan

Reputation: 13227

It returns the Boolean value of a variable.

Instead, the Boolean class can be used.

(Please read the code descriptions.)

var X = "test"; // The X value is "test" as a String value
var booleanX = !!X // booleanX is `true` as a Boolean value because 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

let a = 0
console.log("a: ", a) // Writes a value in its kind
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.
console.log("!!a: ", !!a) // Writes 0 value in Boolean. 0 means false.
console.log("Boolean(a): ", Boolean(a)) // Equals `!!a`
console.log("\n") // Newline

a = 1
console.log("a: ", a)
console.log("!a: ", !a)
console.log("!!a: ", !!a) // Writes 1 value in Boolean
console.log("\n") // Newline

a = ""
console.log("a: ", a)
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.
console.log("!!a: ", !!a) // Writes "" value in Boolean
console.log("\n") // Newline

a = "test"
console.log("a: ", a) // Writes a value in its kind
console.log("!a: ", !a)
console.log("!!a: ", !!a) // Writes "test" value in Boolean

console.log("Boolean(a) === !!a: ", Boolean(a) === !!a) // writes true

Upvotes: 6

Alireza
Alireza

Reputation: 104870

!! is using the NOT operation twice together. ! converts the value to a Boolean and reverses it, so using it twice, showing the Boolean (false or true) of that value. 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, !! makes us sure the value we get is Boolean, not falsy, truthy, string, etc...

So it's like using the Boolean function in JavaScript, but an easier and shorter way to convert a value to Boolean:

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

Upvotes: 32

Mystical
Mystical

Reputation: 2783

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

console.log(Boolean(null)); // Preferred over the Boolean object

console.log(new Boolean(null).valueOf()); // Not recommended for converting non-Boolean values

console.log(!!null); // A hacky way to omit calling the Boolean function, but essentially does the same thing.


// The context you saw earlier (your example)
var vertical;

function Example(vertical)
{
        this.vertical = vertical !== undefined ? !!vertical :
        this.vertical;
        // 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).

        return this.vertical;
}

console.log("\n---------------------")

// vertical is currently undefined

console.log(new Example(vertical).vertical); // The falsy or truthy value of this.vertical
console.log(!!new Example(vertical).vertical); // Coerced value of this.vertical

vertical = 12.5; // Set vertical to 12.5, a truthy value.
console.log(new Example(vertical).vertical); // The falsy or truthy value of this.vertical which happens to be true anyway
console.log(!!new Example(vertical).vertical); // Coerced value of this.vertical

vertical = -0; // Set vertical to -0, a falsy value.
console.log(new Example(vertical).vertical); // The falsy or truthy value of this.vertical which happens to be false either way
console.log(!!new Example(vertical).vertical); // Coerced value of this.vertical

Falsy values in JavaScript coerce to false, and truthy values coerce to true. Falsy 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 falsy, 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).

var vertical = document.getElementById("vertical");
var p = document.getElementById("result");

function Example(vertical)
{
        this.vertical = vertical !== undefined ? !!vertical :
        this.vertical;

        return this.vertical;
}

document.getElementById("run").onclick = function()
{

  p.innerHTML = !!(new Example(eval(vertical.value)).vertical);

}
input
{
  text-align: center;
  width: 5em;
}

button
{
  margin: 15.5px;
  width: 14em;
  height: 3.4em;
  color: blue;
}

var
{
  color: purple;
}

p {
  margin: 15px;
}

span.comment {
  color: brown;
}
<!--Vertical I/O Example-->
<h4>Vertical Example</h4>
<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>
<br />
<button id="run">Run</button>
<p id="result">...</p>

Upvotes: 5

Wouter Vanherck
Wouter Vanherck

Reputation: 2327

After seeing all these great answers, I would like to add another reason for using !!. Currently 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();
}

Upvotes: 7

Abhay Dixit
Abhay Dixit

Reputation: 1018

Use the logical not operator two times.

It means !true = false and !!true = true.

Upvotes: 6

GreQ
GreQ

Reputation: 999

I think worth mentioning is that a condition combined with logical AND/OR will not return a Boolean value, but the last success or first fail in case of && and the first success or last fail in case of || of the 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

Upvotes: 25

Greg Gum
Greg Gum

Reputation: 38049

!!x is shorthand for Boolean(x).

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

Upvotes: 11

GibboK
GibboK

Reputation: 73988

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 leads to the following idiom that you can see in your source code:

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

Upvotes: 5

Here is a piece of code from AngularJS:

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 the 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 assigned undefined then !requestAnimationFrame would be true and one more ! of it would be false.

Upvotes: 6

Warren Davis
Warren Davis

Reputation: 333

There are tons of great answers here, but if you've read down this far, this helped me to 'get it'. Open the console in 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.

Upvotes: 11

Sergey Ilinsky
Sergey Ilinsky

Reputation: 31545

It is double Boolean negation. It is often used to check if a value is not undefined.

Upvotes: 12

Justin Johnson
Justin Johnson

Reputation: 31300

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);

Upvotes: 21

Christoph
Christoph

Reputation: 169723

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

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

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

Upvotes: 95

user7675
user7675

Reputation:

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

Upvotes: 26

Bill the Lizard
Bill the Lizard

Reputation: 405995

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.

Upvotes: 32

Crescent Fresh
Crescent Fresh

Reputation: 117008

!! 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 its "truth" value is.

Upvotes: 122

Darren Clark
Darren Clark

Reputation: 3033

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 you would use !!.

Upvotes: 17

Steve Harrison
Steve Harrison

Reputation: 125640

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

var foo = "Hello, World!";

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

Upvotes: 34

Greg
Greg

Reputation: 321796

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

true === !!10

false === !!0

Upvotes: 68

Ryan Taylor
Ryan Taylor

Reputation: 13465

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 above (b && b.foo) is (b || {}).foo. Those are equivalent, 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.

Upvotes: 12

Related Questions