2

I often see code that uses !!condition as opposed to just the regular condition. I.e.:

if(!!value){
    doSomething();
}

versus:

if(value){
    doSomething();
}

What is the funcational difference, if there is one? Is one superior to the other? What, if any, are the conditions for picking to use one versus the other?

Fourth
  • 9,163
  • 1
  • 23
  • 28
  • possible duplicate of [Can someone explain this 'double negative' trick?](http://stackoverflow.com/questions/4686583/can-someone-explain-this-double-negative-trick) – Jonathan Naguin Nov 06 '13 at 17:23
  • See also [How to use the double not (!!) operator in javascript](http://stackoverflow.com/q/2174297/1048572) – Bergi Jul 19 '14 at 17:46
  • @JonathanNaguin: No it's not. – Bergi Jul 19 '14 at 17:47
  • See also [Why use `!!` to coerce a variable to boolean for use in a conditional expression?](https://stackoverflow.com/q/18648179/1048572) – Bergi Aug 04 '17 at 06:52

3 Answers3

9

Technically nothing. The double bang !! type converts value to a boolean - something the if statement does when it evaluates value anyway.

In the code you have posted, the !! is useless and serves no purpose.

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
7

This is just a more explicit way to test the "truthiness" of a value.

The following will "cast" value to a boolean.

!!(value)

For example, a non-empty string

!!"a" // true

Another example with an empty string

!!"" // false

However, if you simply test a value directly using

if (value) // ...

then the following values are false in JavaScript

  • 0
  • -0
  • null
  • "" (empty string)
  • false
  • undefined
  • NaN

everything else is true

Mulan
  • 129,518
  • 31
  • 228
  • 259
  • When used in if condition it may not be meaningful but when used as a return value, it can be used to send the boolean value. I think this should be the accepted answer. – Gokul N K Sep 16 '14 at 05:20
1

The !! ensures the resulting type is a boolean (true or false).

javascript:alert("foo") --> foo

javascript:alert(!"foo") --> false

javascript:alert(!!"foo") --> true

javascript:alert(!!null) --> false

They do this to make sure $('row') isn't null.

It's shorter to type than $('row') != null ? true : false.

Diego Claudiu
  • 332
  • 1
  • 9