What is the purpose of a β€œcast” return from a boolean operator?

From underscore :

_.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; 

What is the purpose !! . He believed that the result and statement is always true or false.

I saw that it was used as a way to "cast" to the Boolean type.

But I would not think that it is not necessary here.

+4
source share
2 answers

Threesome !! ensures that the conclusion is true or false.

The expression obj && .. will result in the value obj when obj evaluates to false-y (for example, "" or 0).

Sometimes the input objects are not related to the result, and this "casting" (this is not casting at all, but rather coercion) clears the API and avoids leakage of details - we can guarantee that only true or false is returned.

Here is the TTL for a && b , note that the result is not necessarily true or false:

 aba && 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 often use:

 return obj ? obj.nodeType === 1 : false; 
+6
source

Note that if obj is 0, NaN, null, undefined, or an empty string, the expression will evaluate this, not false . If you need to make sure that an explicit boolean is returned, you need to throw.

+3
source

Source: https://habr.com/ru/post/1479051/


All Articles