1

What is the difference if("test") and if(!!"test"), only judged the false or true;

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
user410648
  • 27
  • 1

4 Answers4

6

The question has a double negation expressson, that converts the type to boolean.

e.g.

var x = "test";

x === true; // evaluates to false

var x = !!"test";

x === true; //evalutes to true
naikus
  • 24,302
  • 4
  • 42
  • 43
6

!! will convert a "truthy" value in true, and a "falsy" value on false.

"Falsy" values are the following:

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

If a variable x has any of these, then !!x will return false. Otherwise, !!x will return true.

On the practical side, there's no difference between doing if(x) and doing if(!!x), at least not in javascript: both will enter/exit the if in the same cases.

EDIT: See http://www.sitepoint.com/blogs/2009/07/01/javascript-truthy-falsy/ for more info

kikito
  • 51,734
  • 32
  • 149
  • 189
1

!! does type conversion to a boolean, where you are just dropping it in to an if, it is AFAIK, pointless.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

There is no functional difference. As others point out,

!!"test"

converts to string to a boolean.

Think of it like this:

!(!("test"))

First, "test" is evaluated as a string. Then !"test" is evaluated. As ! is the negation operator, it converts your string to a boolean. In many scripting languages, non-empty strings are evaluated as true, so ! changes it to a false. Then !(!"test") is evaluated, changing false to true.

But !! is generally not necessary in the if condition as like I mention it already does the conversion for you before checking the boolean value. That is, both of these lines:

if ("test")
if (!!"test")

are functionally equivalent.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356