JAVASCRIPT - Ternary (Conditional) Operator and Style

If you hate the ternary conditional operator in the first place, there's no need to reply ;)

I usually see this used in tandem with an assignment expression like:

var foo = (some_condition) ? then_code : else_code;

However, I'd like to use it to replace simple code like:

if(some_condition) {
  do_something_simple;
} else {
  do_something_else;
}

and instead do:

(some_condition) ? do_something_simple : do_something_else;

I'm likely to be doing this in JavaScript. In the above it returns undefined so it doesn't require the assignment. I like the space saved but wonder what folks think on this type of use as, again, I usually only see ternary used with an assignment.

EDIT: I've seen answers alluding to "hiding intent". Although classically used in expressions, how is this hiding the intent any more then using in an expression? Especially in a dynamic language where one may see the use of ternary operators all over the place?

This question and answers originated from www.stackoverflow.com
Question by (11/6/2010 2:10:43 PM)

Answer

The conditional operator should normally be used in expressions - value producing expressions - and is best not used as a replacement for the 'if/then/else' statement. Used occasionally, there'd be no particular problem; used systematically, I think it would be hiding the intent of the code from the readers.


Find More Answers
Related Topics  javascript  coding-style  ternary-operator
Related Questions