4 ms·
Simply, no. I prefer to think in boolean expressions rather than sequences of statements. Personally, I'd further reduce it to (assuming there's no JavaScript s
by scott_s 16y ago
Simply, no. I prefer to think in boolean expressions rather than sequences of statements. Personally, I'd further reduce it to (assuming there's no JavaScript subtleties I'm missing here; in C/C++ this would have the same semantics):
function getEventTarget(evt) {
return (evt || window.event) && (evt.target || evt.srcElement);
}
A boolean expression is straight-up math, and I've been trained to reason about that. With a sequence of statements, I have to first figure out what you're doing, then extrapolate the implications. The implications stare me in the face when I look at a boolean expression.
- WesleyJohnson 16y agoIn the OP's example, evt will retain it's value if passed in as "truthy" or take on the value of window.event otherwise. The return then returns evt and evt.target or evt.srcElement which may from the original passed in evt or really from window.event, which was assigned to evt in the first line. With your example, evt.target and evt.srcElement are only coming from the passed in evt which may have been passed in as "falsey" and would not take on the target or srcElement of window.event as intended. I could be mistaken, it's late and I'm rusty. Anyone is free to correct me.
- gruseom 16y agoBut that crashes on null in all three languages, no? (i.e. if evt is null and window.event is non-null.) I suppose you could do this: function getEventTarget(evt) { return (evt || (evt = window.event)) && (evt.target || evt.srcElement); } But that's probably more trouble than it's worth. Anyway, I agree with you in preferring expressions to statements on the whole. It's hard to imagine why anyone would prefer the more than 4x as long version in the OP; to me it reads like a parody.