Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 890
Rob Avatar asked Nov 06 '10 14:11

Rob


People also ask

How do you write a 3 condition ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

Can you use a ternary operator in CSS?

The inner set of curly braces is the object of CSS properties and values. If you have multiple properties whose values are determined by the same condition, you could use the ternary operator to return an entire object of properties and values.

How are ternary operators used in styled components?

Ternary Operator with Styled Components div` position: fixed; width: 200px; max-width: 70%; height: 100%; left: 0; margin-top: 1.4rem; z-index: 200; background-color: white; padding: 1rem 2rem; transition: all 0.7s ease; box-shadow: 0px 8px 30px rgba(0, 0, 0, 0.2); display:${props => props.


1 Answers

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.

like image 71
Jonathan Leffler Avatar answered Sep 25 '22 13:09

Jonathan Leffler