1

Let's suppose I have a variable condition. If I want to store it into a variable as a strict boolean value, then I do something like this:

var logicalCondition = !!condition;

The first exclamation negates condition and converts the value into a boolean. The second exclamation negates the negated strict boolean value back. The result is true if condition was truey and is false if condition is falsy. If conditions are known to convert truey to true and falsy to false. So, if we take a look at the following two chunks

//first
if (condition) {
    //do something
}

//second
if (!!condition) {
    //do something
}

the first difference we can observe is that in the second case we convert the value into strict boolean value before we hand it to the if. Is there a second difference, or is this conversion unnecessary?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • 1
    No difference. `!!` is an implicit conversion to boolean but `if(condition)` also takes truthy/falsey values and it does the same either way – VLAZ Aug 07 '16 at 13:49
  • It is unnecessary. The behavior of the `if` condition test is exactly the same as the result of `!!`. – Pointy Aug 07 '16 at 13:49
  • May be linter less complains with that? like automatic type detection and it is not boolean. – YOU Aug 07 '16 at 13:49
  • 1
    I just like to point out that while `if(!!condition)` is superflous, it works to instruct the next person who looks at the code that `condition` is not actually a boolean. So, it has some value for maintenance, even if there is no difference for the performance. – VLAZ Aug 07 '16 at 13:51

1 Answers1

1

Is there a second difference...?

No, there isn't, at the JavaScript engine's level. As you've said, the test done by if (and anywhere else a boolean is required) will do the same thing that !! is doing (in effect). So your first difference (the extra work) is the only difference.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875