JAVASCRIPT - Ternary (Conditional) Operator and Style
العربية
български
català
中文
čeština
dansk
Nederlands
eesti
suomi
français
Deutsch
Ελληνικά
עברית
हिंदी
magyar
Bahasa Indonesia
italiano
日本語
한국어
latviešu
lietuvių
norsk
polski
Português
română
русский
slovenčina
slovenski
español
svenska
ไทย
Türkçe
українська
Tiếng Việt
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?
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.