admin管理员组文章数量:1417426
I've a legacy script. This is a part from it:
var e = e ? e : event;
So, nothing wrong here. But I use ternary mainly for toogling. Can it safely be rewritten like this
var e = e || event;
Is there any hidden reason for not using this one?
I've a legacy script. This is a part from it:
var e = e ? e : event;
So, nothing wrong here. But I use ternary mainly for toogling. Can it safely be rewritten like this
var e = e || event;
Is there any hidden reason for not using this one?
Share Improve this question edited Dec 11, 2017 at 13:00 Hitmands 14.2k4 gold badges40 silver badges77 bronze badges asked Dec 10, 2012 at 13:54 shagonshagon 3031 gold badge4 silver badges14 bronze badges 7- 4 I find the first more readable. – Anirudh Ramanathan Commented Dec 10, 2012 at 13:58
-
I find the second more readable, and there's been this exact dispute last month (I'll try to find it but it's going to be hard). Also don't forget the simplest
if (!e) e = event;
. – Kos Commented Dec 10, 2012 at 14:01 -
1
@Cthulhu Both expressions are very simple, so readability cannot be an issue here. It seems that you're not used to working with the
||
operator. It's used regularly for these types of checks. I'd ditch the parens, though. – Šime Vidas Commented Dec 10, 2012 at 14:01 -
1
Is
e
a parameter of the current function? If yes, there's no need to declare a variable with that same name viavar
. – Šime Vidas Commented Dec 10, 2012 at 14:03 -
@Kos
if (!e) e = event;
is the way to go. Unlike in OP's examples, here the assignment is only made if necessary. – Šime Vidas Commented Dec 10, 2012 at 14:06
2 Answers
Reset to default 7In your example e
will be used if it is NOT a falsy value, such as false, 0, "", null, undefined
. Otherwise event
will be used. In your case this should be save.
But there is some danger in using more plex logical expressions instead of if-then-else (or ternary). Here is an example:
result = value > 10 && getA() || getB()
If the guard value > 10
evaluates to true
AND getA()
returns a falsy value, then getB()
will be returned. This is different from the if-then-else behavior, which would return the falsy result of getA()
.
Gotta be carefull with the second option, you're basically expecting that if 'e' is anything but false, it'll assign it to your local 'e', otherwise, you'll use 'event', but if, for instance, 'e' is "0", what would you want your local 'e' to have? "0" or 'event'? Because in your case, your local 'e' would end up with 'event' anyways.
本文标签: javascriptLogical or instead of ternaryStack Overflow
版权声明:本文标题:javascript - Logical or instead of ternary - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745265748a2650588.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论