Is !! a best practice to check a truthy value in an if statement

37.4k Views Asked by At

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);
}

2

There are 2 best solutions below

4
On BEST ANSWER

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) {
3
On

!!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.