I've seen code like this on the web:
function MyEventHandler(e)
{
var ev = e || event;
var target = ev.srcElement || ev.target
}
In essence, the ||
operator is used as a shorthand for a?a:b
. As far as I can tell - it works on all browsers. But bringing up specs for, say, JScript, I see:
Performs a logical disjunction on two expressions.
and
JScript uses the following rules for converting non-Boolean values to Boolean values:
- All objects are considered true.
So... according to this the result should be a boolean true/false. I'm just wondering - am I walking the knife-edge of undocumented behavior, or is there some fine implication here that I haven't picked up?
That behavior is quite well documenten. See Chapter 11.11 of the ECMAScript Specification: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf
Unfortunately it's not very easy to understand, however the last paragraph states:
The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.
No, I think you understand the coalescent behavior of ||
just fine.
EDIT:
&&
is also coalescent. a && b
behaves like a ? b : a
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With