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;