Reputation: 2784
I am looking at a piece of code which detects IE browser:
if (false || !!document.documentMode)
and I am not understanding the contraption. Why is it necessary to OR with false and use NOT twice?
If I simply loaded below file in IE9, FF or Opera, then IE would tell me that document mode was there, while the later two would say otherwise:
<html>
<head>
<script>function ld() {
if (document.documentMode){
document.getElementById("p1").innerHTML = 'Document Mode detected'
}
else {
document.getElementById("p1").innerHTML = 'No Document Mode'
}
}</script>
</head>
<body onload="ld()">
<p id="p1"></p>
</body>
</html>
Is that not sufficient and why? It is not clear, because if I replaced the condition with the one in my original question, the result would be exactly the same. What am I missing?
Upvotes: 1
Views: 766
Reputation: 123473
Why is it necessary to OR with false [...]
It isn't necessary. The ||
operator, given false
for the 1st operand, will always return the 2nd operand.
// lval || rval (minus short-circuiting)
function OR(lval, rval) {
if (lval)
return lval;
else
return rval;
}
OR(false, 'foo') // 'foo'
[...] and use NOT twice?
This part already has an answer here on SO.
Two !
operators together perform a "ToBoolean" type conversion, as a slighter shorter version of using Boolean()
without new
:
!!document.documentMode // true/false
Boolean(document.documentMode) // true/false
Also, the if
will perform the same type conversion itself.
2. If ToBoolean(GetValue(exprRef)) is true
So, when testing a single value for truthiness, the !!
aren't necessarily either, as you suggested:
if (document.documentMode)
Upvotes: 2
Reputation: 35670
Since document
is always defined, and the presence of its property documentMode
is truthy, these are completely synonymous:
if (false || !!document.documentMode)
and:
if(document.documentMode)
(If document
was possibly undefined, then the first code would fail altogether.)
Upvotes: 1