Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double negation (!!) in javascript - what is the purpose? [duplicate]

Tags:

javascript

People also ask

What is the use of double negation in JavaScript?

The double-negation !! is not a distinct JavaScript operator nor a special syntax but rather just a sequence of two negations. It is used to convert the value of any type to its appropriate true or false Boolean value depending on whether it is truthy or falsy.

What does double negation do?

It first negates the result of the expression, then it negates it again. In this way if you had a non-zero number, a string, an object, an array, or anything that's truthy, you'll get true back. Otherwise you'll get false .

What is the use of double in JavaScript?

(unless you're writing in JavaScript, in which case it's perfectly ok). The double exclamation point, or double bang, converts a truthy or falsy value to “true” or “false”. In other words, it operates exactly like Boolean(value) would.

What is the use of double operator?

If you place this operator in front of a boolean value, it will reverse the value, returning the opposite. If the single bang returns the opposite boolean value, imagine what double-bang would return? The associated boolean value. In other words, true or false according to whether it is truthy or falsy values.


It casts to boolean. The first ! negates it once, converting values like so:

  • undefined to true
  • null to true
  • +0 to true
  • -0 to true
  • '' to true
  • NaN to true
  • false to true
  • All other expressions to false

Then the other ! negates it again. A concise cast to boolean, exactly equivalent to ToBoolean simply because ! is defined as its negation. It’s unnecessary here, though, because it’s only used as the condition of the conditional operator, which will determine truthiness in the same way.


var x = "somevalue"
var isNotEmpty = !!x.length;

Let's break it to pieces:

x.length   // 9
!x.length  // false
!!x.length // true

So it's used convert a "truethy" \"falsy" value to a boolean.


The following values are equivalent to false in conditional statements:

  • false
  • null
  • undefined
  • The empty string "" (\ '')
  • The number 0
  • The number NaN

All other values are equivalent to true.


Double-negation turns a "truthy" or "falsy" value into a boolean value, true or false.

Most are familiar with using truthiness as a test:

if (options.guess) {
    // runs if options.guess is truthy, 
}

But that does not necessarily mean:

options.guess===true   // could be, could be not

If you need to force a "truthy" value to a true boolean value, !! is a convenient way to do that:

!!options.guess===true   // always true if options.guess is truthy