Can someone explain this 'double negative' trick?
This question already has an answer here:
A logical NOT operator !
converts a value to a boolean that is the opposite of its logical value.
The second !
converts the previous boolean result back to the boolean representation of its original logical value.
From these docs for the Logical NOT operator:
Returns false if its single operand can be converted to true; otherwise, returns true.
So if getContext
gives you a "falsey" value, the !!
will make it return the boolean value false
. Otherwise it will return true
.
The "falsey" values are:
false
NaN
undefined
null
""
(empty string) 0
Javascript has a confusing set of rules for what is considered "true" and "false" when placed in a context where a Boolean is expected. But the logical-NOT operator, !
, always produces a proper Boolean value (one of the constants true
and false
). By chaining two of them, the idiom !!expression
produces a proper Boolean with the same truthiness as the original expression.
Why would you bother? Because it makes functions like the one you show more predictable. If it didn't have the double negative in there, it might return undefined
, a Function
object, or something not entirely unlike a Function
object. If the caller of this function does something weird with the return value, the overall code might misbehave ("weird" here means "anything but an operation that enforces Boolean context"). The double-negative idiom prevents this.
In javascript, using the "bang" operator (!) will return true if the given value is true, 1, not null, etc. It will return false if the value is undefined, null, 0, or an empty string.
So the bang operator will always return a boolean value, but it will represent the opposite value of what you began with. If you take the result of that operation and "bang" it again, you can reverse it again, but still end up with a boolean (and not undefined, null, etc).
Using the bang twice will take a value that could have been undefined, null, etc, and make it just plain false
. It will take a value that could have been 1, "true", etc. and make it just plain true
.
The code could have been written:
var context = document.createElement('canvas').getContext;
var contextDoesNotExist = !context;
var contextExists = !contextDoesNotExist;
return contextExists;
链接地址: http://www.djcxy.com/p/12638.html
上一篇: 双感叹号?
下一篇: 有人可以解释这种“双重否定”的伎俩吗?