What is the !! (not not) operator in JavaScript?

Viewed 829994

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;
41 Answers

It converts Object to boolean. If it was falsey (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 may be 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

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

true === !!10

false === !!0

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

var foo = "Hello, World!";

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

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.

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

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.

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

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:

if (value) {
  value2 = true;
} else {
  value2 = 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 than zero, not empty strings, {}, [] and new Date() so,

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

!! is simply the NOT operator twice. The net effect is just converting anything to ensure a Boolean data type. For example.

!!undefined is false
!!0 is false
!!null is false
!!anyobject is true
!!true is true
!!false is false
!0 is true
!1 is false
!!'' is false

!! is not an operator. It's just the ! operator twice.

But with JavaScript, apply !! for converting Object to Boolean is redundant and verbose in the most cases because:

Any object of which the value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement

Example: if ({}) { console.log("{} is true")} // logs: "{} is true"

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 the user has a major or not and we have a function just like:

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

But the answer is not important to us. We just want to check if it has a major or not and we need a Boolean value (true or false). How do 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 returns false, but because the value has exits and we need to return true, we use ! twice to return the correct answer, !(!this.major).

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

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

Just to check if exist

if(!!isComplianceOnHold){
//write code here is not undefined
//if isComplianceOnHold is undefined or null will not enter in net is false
// if isComplianceOnHold is not null or even boolean net result is true and enter inside if block
}

Any object of which the value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement

This is the simplest answer I've found: It is equivalent to Boolean(value) in how it works.

Related