What is the difference if("test") and if(!!"test"), only judged the false or true;
views:
114answers:
4!! does type conversion to a boolean, where you are just dropping it in to an if, it is AFAIK, pointless.
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
!! 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
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.