Javascript ! and !! differences [duplicate]
Possible Duplicate:
What is the !! operator in JavaScript?
What is the difference between these two operators? Does !! have special meaning, or does it simply mean yo开发者_如何学运维u are doing two '!' operations. I know there are "Truth" and "Truthy" concepts in Javascript, but I'm not sure if !! is meant for "Truth"
!! is just double !
!true // -> false
!!true // -> true
!! is a common way to cast something to boolean value
!!{} // -> true
!!null // -> false
Writing !!
is a common way of converting a "truthy" or "falsey" variable into a genuine boolean value.
For example:
var foo = null;
if (!!foo === true) {
// Code if foo was "truthy"
}
After the first !
is applied to foo
, the value returned is true
. Notting that value again makes it false
, meaning the code inside the if
block is not entered.
精彩评论