3

Normally, I compare a boolean value by simply putting it in if statement as following:

var foo = 'Foo data';
if ( foo ) {
    // Do somethings
}

Recently, I just saw some people convert the variable to boolean before comparing it:

if ( !!foo ) { 
    // Do somethings
}

Is there any different in term of performance or advantage? Which one is more preferable?

lvarayut
  • 13,963
  • 17
  • 63
  • 87
  • 1
    Just how you want it ... [check this](http://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript) .. – Mihai Iorga Jan 15 '15 at 13:11
  • 2
    [This blog post](http://james.padolsey.com/javascript/truthy-falsey/) seems relevant and helpful. – Sukima Jan 15 '15 at 13:19

3 Answers3

7

There is no functional difference in comparison, as seen in this fiddle http://jsfiddle.net/aeujgovd/1

if(foo){}
if(!!foo){}

The only reason to use !! is to coerce a boolean value from a truthy/falsey value for example, if your API is expecting a proper boolean rather than a flag like 0 or 1.

var myObj = {flag: 0};
function submitObj(myObj){
    myObj.flag = !!myObj.flag;
    // ... Ajax submit
}
Scottux
  • 1,577
  • 1
  • 11
  • 22
4

From the section 12.5 of the ECMAScript Language Specification:

12.5 The if Statement

...

The production IfStatement : if ( Expression ) Statement is evaluated as follows:

  1. Let exprRef be the result of evaluating Expression.
  2. If ToBoolean(GetValue(exprRef)) is false, return (normal, empty, empty).
  3. Return the result of evaluating Statement.

From this we can see that ToBoolean() is used on the passed in expression regardless of whether it's already a Boolean value or not.

Because of this I'm going to say that it's very unlikely that if (foo) will cause any more of a performance hit than if (!!foo), and that the two extra bytes caused by the two ! characters in your JavaScript file would probably outweigh any bonus from converting the value to a Boolean within the if statement anyway.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
0

If you can avoid conversion ... it's always better in terms of performance. If all you want to achieve is to check if foo is null, I would choose the first option.

Georgi
  • 189
  • 2
  • 12