What is the purpose of "casting" the return from a Boolean operator?
javascript, underscore.js
Solution
The `!!` trick ensures the output is true or false.
The expression `obj && ..` will result in the value of obj when obj evaluates to a false-y value (such as "" or 0).
Sometimes the input objects are not relevant to the result and this "casting" (it's not casting at all, but rather a coercion) cleans up the API and avoids leaking details - it can be assured that only true or false is returned.
Here is the TTL for `a && b`, note the result is not necessarily true or false:
a b a && b
------- ------ ------
TRUTH-y ANY b
FALSE-Y ANY a
Here is the TTL for `!e`, the result is always true or false:
e !e !!e
------- ------ ------
TRUTH-y false true
FALSE-y true false
An alternative way to express the original expression, which I actually use often:
return obj ? obj.nodeType === 1 : false;
Problem
From underscore: ``` _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; ``` What is the purpose of `!!`. It thought the result of an and statement was always true or false. I've seen this used as way to "cast" to a Boolean type. But I would not think it is not necessary here.