1

What is the best way to get the boolean value of an expression?

I usually use !!, wonder if there is any reason to use it over Boolean or if it's ok to use either of those.

someFunction: function(param){
  var myBoolean = !!param;
}

But I can also do:

someFunction: function(param){
  var myBoolean = Boolean(expression); 
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

code4jhon
  • 5,725
  • 9
  • 40
  • 60
  • 1
    I think it's just like `Number(value)` vs `+value`. One is considered easier to read, and the other is faster. – Lewis May 01 '15 at 13:54

2 Answers2

2

Both do the same usually. They differ in the following points:

  • !! is only two characters to type
  • Boolean is explicit and can be understood even by people who don't know the "!! operator"
  • Boolean could be overwritten, whereas !! is always safe
  • !! seems to be better optimised

So use whatever you like better.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

I tried the following snippets in the consoles of Safari (8.0.5), Chrome (42.0.2311.90), Firefox (34.0.5) and Opera (29.0.1795.47):

With !!:

var time = new Date().getTime();
for(var i = 0; i < 1000000; i++)
{
    var a = true;
    a = !!a;
}
time = new Date().getTime() - time;
console.log(time);

With Boolean():

var time = new Date().getTime();
for(var i = 0; i < 1000000; i++)
{
    var a = true;
    a = Boolean(a);
}
time = new Date().getTime() - time;
console.log(time);

No matter what I set a to before using !! or Boolean, in all browsers !! was faster.

In addition to this (as Bergi already said in his answer), Boolean is just a variable that has to be resolved and can be overwritten, while !! cannot be.

Boolean() is more reader-friendly though.

So what is actually better is a question of opinion, but I would say performance and safety together outweigh readability, so I prefer !!.

Siguza
  • 21,155
  • 6
  • 52
  • 89