开发者

What is the difference if("test") and if(!!"test")

What is the difference if("t开发者_如何学Cest") and if(!!"test"), only judged the false or true;


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:

  • 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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜