Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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);  }
like image 921
Bargitta Avatar asked Nov 13 '14 10:11

Bargitta


People also ask

How do you check for truthy?

To check if a value is truthy, pass the value to an if statement, e.g. if (myValue) . If the value is truthy, it gets coerced to true and runs the if block. Copied! In our if statement, we check if the value in the myVar variable is truthy.

How do you know if something is truthy or Falsy?

Truthy values are values that evaluate to True in a boolean context. Falsy values are values that evaluate to False in a boolean context. Falsy values include empty sequences (lists, tuples, strings, dictionaries, sets), zero in every numeric type, None , and False .

How do you determine Falsy value?

Use the logical NOT (!) operator to check if a value is falsy, e.g. if (! myValue) . The logical NOT operator returns true when it precedes falsy values, in all other cases it returns false .

What does it mean for a value to be truthy?

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false , 0 , -0 , 0n , "" , null , undefined , and NaN . JavaScript uses type coercion in Boolean contexts.


2 Answers

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

like image 188
Timothy Shields Avatar answered Oct 02 '22 15:10

Timothy Shields


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) { 
like image 27
Denys Séguret Avatar answered Oct 02 '22 17:10

Denys Séguret