Take the 2-minute tour ×

I have found two ways of coding a conditional assignment, but both give the same result:

function onClickEvent(e){ 
    e = win.event || e,  //These are
    var ev=e.target || e.srcElement;  // good?


function onClickEvent(e){
    e = (win.event) ? win.event : e;  //or
    var ev = (e.target) ? e.target : e.srcElement; // these are?

Is one approach preferred over the other? If yes, why?

share|improve this question
They both work, and there's not even a functional difference. Use whichever you like. –  deceze Feb 22 '13 at 18:42
It doesn't matter. Do whatever you prefer, or which suits you most. If you work as part of a team, negotiate the standards you should all follow, and then follow those. –  David Thomas Feb 22 '13 at 18:44
add comment

closed as not constructive by deceze, sachleen, David Thomas, Teemu, Dave Newton Feb 22 '13 at 19:18


2 Answers

up vote 2 down vote accepted

Use the shortest, most communicative code possible.

IMO the first is canonical JS for optional argument assignment and would be preferred.

The second, while equivalent, requires more effort to comprehend, unless you're conversant in JavaScript. If you opt for the latter, please use more whitespace and drop the parens.

share|improve this answer
add comment

I would say, the second one, because it is more readable and common-sensical.

share|improve this answer
It's not a matter of "common sense"; the first is idiomatic JS. That doesn't automatically confer readability, but it's not "common sense" to ignore idiomatic language constructs. (IMO) –  Dave Newton Feb 22 '13 at 18:58
Common Sense means, commonly available sense, meaning, it is in the format which is more likely to be recognizable by more people. Upvoted you, btw ;-) –  srini.venigalla Feb 22 '13 at 19:03
I agree to use the second one, it's more readable and is used in other languages (like C#). That's my opinion. –  contactmatt Feb 22 '13 at 19:09
@contactmatt So developers should code to the "lowest common denominator" and only use features found in language Xyz? That doesn't make any sense. –  Dave Newton Feb 22 '13 at 19:18
@srini.venigalla And idiomatic JS is the simpler. –  Dave Newton Feb 22 '13 at 20:40
show 2 more comments
