Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this expression mean "!!"

Tags:

javascript

Why would somebody use an expression like

if(!!window.JSON) alert('exists');

instead of just

if(window.JSON) alert('exists');

?

Is there another usage for the "!!" thing ?

like image 573
Alex Avatar asked Jun 17 '10 07:06

Alex


3 Answers

!! will simply cause a boolean conversion, it is not necessary at all to use this construct with the if statement, also in your first snippet, converting an object to boolean makes no sense, it will be always true.

The only values that can coerce to false are null, undefined, NaN, 0, and empty string and of course false anything else will coerce to true.

When it makes sense to use !! is when you want to make sure to get a boolean result, for example when using the Logical && and || operators.

Those operators can return the value of an operand, and not a boolean result, for example:

true && "foo"; // "foo"
"foo" || "bar" ; // "foo"

Imagine you have a function that test two values, and you expect a boolean result:

function isFoo () {
  return 0 && true;
}

isFoo(); // returns 0, here it makes sense to use !!

Edit: Looking at your edit, if (!!window.JSON) is just redundant as I said before, because the if statement by itself will make the boolean conversion internally when the condition expression is evaluated.

like image 145
Christian C. Salvadó Avatar answered Sep 28 '22 09:09

Christian C. Salvadó


They're probably trying to cast the object to a boolean. By applying a boolean operator (!) to the object, it becomes a bool, but they don't actually want the negation, so they apply a second one to cancel the first.

like image 34
mpen Avatar answered Sep 28 '22 07:09

mpen


// !! = boolean typecasting in javascript

var one = 1
var two = 2;

if (one==true) app.alert("one==true");
if (!!one==true) app.alert("!!one==true");

if (two==true) app.alert("two==true"); // won't produce any output
if (!!two==true) app.alert("!!two==true");
like image 33
o-o Avatar answered Sep 28 '22 07:09

o-o