Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 you are doing two '!' operations. I know there are "Truth" and "Truthy" concepts in Javascript, but I'm not sure if !! is meant for "Truth"

like image 653
void.pointer Avatar asked May 30 '11 14:05

void.pointer


2 Answers

!! is just double !

!true // -> false
!!true // -> true

!! is a common way to cast something to boolean value

!!{}  // -> true
!!null // -> false
like image 101
bjornd Avatar answered Oct 25 '22 05:10

bjornd


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.

like image 27
Andrew Whitaker Avatar answered Oct 25 '22 05:10

Andrew Whitaker