29

In angular.js, there are some code snippets use !! to check whether a value is truthy in if condition.

Is it a best practice? I fully understand in return value or other assignment !! is used to make sure the type is Boolean. But is it also true for condition checks?

if (!!value) {
  element[name] = true;
  element.setAttribute(name, lowercasedName);
} else {
  element[name] = false;
  element.removeAttribute(lowercasedName);
}
Paolo
  • 20,112
  • 21
  • 72
  • 113
Bargitta
  • 2,266
  • 4
  • 22
  • 35

2 Answers2

55

!!value is commonly used as a way to coerce value to be either true or false, depending on whether it is truthy or falsey, respectively.

In a control flow statement such as if (value) { ... } or while (value) { ... }, prefixing value with !! has no effect, because the control flow statement is already, by definition, coercing the value to be either true or false. The same goes for the condition in a ternary operator expression value ? a : b.

Using !!value to coerce value to true or false is idiomatic, but should of course only be done when it isn't made redundant by the accompanying language construct.

Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
  • 8
    This is a better answer then the other one which states that it is totally useless. As you point out, there is a use case for those rare times when you do need to coerce the expression to `true` or `false`, for example when a function expects a boolean argument. – Sunil D. Nov 16 '14 at 01:16
  • 4
    @SunilD. Please read the question against : `" in if condition"`. – Denys Séguret Nov 17 '14 at 12:42
  • Is this a valid/proper use case for **!!** `const validData = [value1, value2, .....].filter(val => !!val);` where validData is an array having only the truthy values – Johnson Jul 09 '18 at 07:34
45

No, !! is totally useless in a if condition and only confuses the reader.

Values which are translated to true in !!value also pass the if test because they're the values that are evaluated to true in a Boolean context, they're called "truthy".

So just use

if (value) {
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 3
    Yes, it's useless in javascript. – Jashwant Nov 16 '14 at 06:48
  • 1
    Agreed w/r/t control flow, but there is use in doing this in the context of a strongly typed system, such as Flow or TypeScipt. I.e. in cases where a function's signature strictly necessitates a `boolean` type. – IliasT Jun 11 '18 at 19:14
  • 5
    @IliasT There are often cases where you *need* a boolean, even in JavaScript. You may also want to provide a boolean to an API managed by somebody's else because it's cleaner and it lets you not have to check how the value is interpreted. When I say it's useless I'm only specifically referring to the use in a `if` condition. – Denys Séguret Jun 11 '18 at 20:05
  • Thanks for the clarification :) – IliasT Jun 12 '18 at 16:02