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?

Alex
  • 5,671
  • 9
  • 41
  • 81
  • 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. – Felix Kling Mar 16 '15 at 23:43
  • `!!someVariable` is the same that `someVariable`. `!!` is like doble negation. – levi Mar 16 '15 at 23:43

2 Answers2

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;
jfriend00
  • 683,504
  • 96
  • 985
  • 979
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.

Miguel Mota
  • 20,135
  • 5
  • 45
  • 64