What is the difference if("test") and if(!!"test"), only judged the false or true;
- 700,868
- 160
- 1,392
- 1,356
- 27
- 1
-
I think I already saw a question like this, but I can't remember the topic – Federico klez Culloca Aug 04 '10 at 10:37
-
1subject of your question is different to the body – Aug 04 '10 at 10:42
-
@tm1rbrt: I fixed it, first editor edited it wrongly. – BoltClock Aug 04 '10 at 10:47
-
See http://stackoverflow.com/questions/1406604/what-does-the-operator-double-exclamation-point-mean-in-javascript – Crescent Fresh Aug 04 '10 at 10:51
-
I believe OP knows what `!!x` does, but the question is whether the two statements are equivalent in behavior. – kennytm Aug 04 '10 at 10:58
-
possible duplicate of [What is the !! (not not) operator in JavaScript?](http://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript) – Andrew Marshall May 06 '12 at 01:57
4 Answers
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
- 24,302
- 4
- 42
- 43
!! will convert a "truthy" value in true, and a "falsy" value on false.
"Falsy" values are the following:
false0(zero)""(empty string)nullundefinedNaN
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
- 51,734
- 32
- 149
- 189
!! does type conversion to a boolean, where you are just dropping it in to an if, it is AFAIK, pointless.
- 914,110
- 126
- 1,211
- 1,335
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.
- 700,868
- 160
- 1,392
- 1,356
-
thanks for you answer, if(!! "var") widely used ,in Ext lib; I think if("var") is equal to if(!! "var"); – user410648 Aug 05 '10 at 01:25