0

I have seen some developers use variables in a way that does not make sense to me, and this is something I have seen more commonly in AngularJS.

Consider this code:

var someVariable = (someOtherVariable === 'true'); if (!!someVariable) { // do some stuff here } 

why not just leave out those two exclamation marks? Is it not the same? What is the benefit of doing it like this?

2
  • Yep, it's the same in this case. And since someVariable is guaranteed to be a Boolean, "casting" it to a Boolean makes even less sense. There is no benefit here at all. Commented Mar 16, 2015 at 23:43
  • !!someVariable is the same that someVariable. !! is like doble negation. Commented Mar 16, 2015 at 23:43

2 Answers 2

2

The double not operator !! coerces a (potentially non-boolean) value to a boolean.

In your specific example:

var someVariable = (someOtherVariable === 'true'); if (!!someVariable) { // do some stuff here } 

someVariable is already guaranteed to be a Boolean (since the result of an === comparison is always a Boolean) so coercing it to a Boolean does not change the operation in any way and is pretty much wasted code. Even if it wasn't already a Boolean, you don't need to coerce it to a Boolean just to test it like if (someVariable) either so there's yet another reason not to use the !! here.

When !! is useful is when you want to store a true Boolean somewhere, but you may only have a truthy or falsey value, not necessarily a true Boolean. Then you can coerce it to a Boolean with the !!.


So, suppose you had some value that is not necessarily a Boolean and you wanted to set some other value to a true Boolean based on the truthy-ness or falsey-ness of the first variable. You could do this:

var myVar; if (someVar) { myVar = true; } else { myVar = false; } 

or this:

myVar = someVar ? true : false; 

or this:

myVar = !!someVar; 
Sign up to request clarification or add additional context in comments.

1 Comment

Yep. if statements coerce the condition value to a Boolean automatically.
1

!! is the double not operator. It coerces the operand to a Boolean.

in terms of conditional statements, if (!!someVariable) { } is the equivalent of if (someVariable) { } because the condition will be met if the value is truthy since there is auto boolean coercion.

2 Comments

I think the OP knows that. The other part of the question is what the difference is and if there is any benefit here.
No readability benefit, thats for sure.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.