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

Javascript

Javascript Problem Overview


> Possible Duplicate:
> What is the !! (not not) operator in JavaScript?

I have encountered this piece of code

function printStackTrace(options) {
    options = options || {guess: true};
    var ex = options.e || null, guess = !!options.guess;
    var p = new printStackTrace.implementation(), result = p.run(ex);
    return (guess) ? p.guessAnonymousFunctions(result) : result;
}

And couldn't help to wonder why the double negation? And is there an alternative way to achieve the same effect?

(code is from https://github.com/eriwen/javascript-stacktrace/blob/master/stacktrace.js)

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEran MedanView Question on Stackoverflow
Solution 1 - JavascriptRy-View Answer on Stackoverflow
Solution 2 - Javascriptgdoron is supporting MonicaView Answer on Stackoverflow
Solution 3 - JavascriptJamie TreworgyView Answer on Stackoverflow