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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745265748a4619443.html
评论列表(0条)