Can I get some clarification on why I would want to use this?
myVar = !!someOtherVar;
Can I get some clarification on why I would want to use this?
myVar = !!someOtherVar;
In non-strictly typed languages, the ! operator converts a value to a boolean. Doing it twice would be equivalent to saying
myVar = (boolean)someOtherVar
Note that this is not recommended for code clarity.
(Rewritten to clarify, simplify)
That statement performs a couple different actions:
myVar = // This portion is a regular assignment, it will store the value of the suffix
!!someOtherVar; // This portion is evaluated to a boolean result
The !!someOtherVar
, I assume, is what you're really asking about. The answer is simple: it performs two logical NOT operations against the truthiness (a Javascript'ism) of someOtherVar
.
In other words, if you understand the !
operator, this just combines two of them (!!
isn't a different operator). By doing this it essentially returns the boolean evaluation of someOtherVar
--in other words, it's a cast from whatever type someOtherVar
is to boolean
.
So... to walk through this, and pay attention to the result of myVar
:
myVar = someOtherVar; // myVar will be whatever type someOtherVar is
myVar = !someOtherVar; // myVar will *always be boolean, but the inverse of someOtherVar's truthiness
myVar = !!someOtherVar; // myVar will *always be boolean, and be the equivalent of someOtherVar's truthiness
It's a double negation, but it also works for type casting. !somevar
will return a boolean (true, if somevar is "falsey" and false if it is "truthy", as per Crockford's lectures). So, !!somevar
will be not(bool)
and hence it will be boolean.
If you need to pass a boolean value to a function, or are anal about evaluating only booleans in conditional statements, that casts someOtherVar
to a boolean for you by double-negating it.