When should I use a double-bang?
I recently reviewed code from a coworker, in which I suggested removing the famous double-bang (`!!`) construct from the return value of a function named `hasFeature()`. The following discussion ensued.
NB: the double-bang construct allows one to coerce (“cast”) a value to a Boolean value, through double negation. It is not an operator in itself, but the repetition of the unary `!` operator, which negates the truthiness of its operand.
'truthy'; // 'truthy'
! 'truthy'; // false
!! 'truthy'; // ! false ⇒ true
So in JS, as long as the code is fine with it, you shouldn’t cast ?
Well, it is a matter of consistency, of course. If your codebase relies on `=== true`, you should obviously cast. On the other hand however, if you do take advantage of truthies and falsies and write `if (hasFeature())`, what’s the point of casting it? Wasting (admittedly very little) CPU and memory?
As soon as you understand that everything in JS can be evaluated to a boolean value, there is little need for actual `Boolean` types, except in domain representations and specific cases where you would have a different treatment for different falsies (such as `undefined` meaning the value has not yet been initialized, as opposed to a `false` value being a domain value).
This doesn’t mean you should avoid `Boolean` values. It simply means `return myVal` has exactly the same truthiness value as `return !! myVal`. The fact that the function name suggests it returns a `true`/`false` value actually suggests it is very safe to return truthies/falsies, as its return value would be only used in a comparison or a condition.
Then again, consistency above all. But if you want to return a `Boolean`, I’d go with a clear, readable cast with `Boolean(result)` where even a JS newbie understands what goes on rather than the cryptic `!! result`.