DEV Community

Cover image for Ternary X LEETcode
Kaleb
Kaleb

Posted on • Updated on

Ternary X LEETcode

Ternary What?

The ternary operator is a unique tool that give us a way to execute code based upon a conditional in our operation. The ternary operator is unique in the matter of its operands:

  • The condition
  • expression executed if condition is truthy
  • expression executed if condition is falsy
condition ? exprIfTrue : exprIfFalse
Enter fullscreen mode Exit fullscreen mode

This gives us a lot of options with a such simple operator, when we realize that we can nest the operators inside of an expression, things get more... complicated.

Right-associative logic

The right-associative logic is a result of grouping and short-circuit execution. The logic is executed in a way that all conditions must met before ANY logic is evaluated inside the expression branch, therefore:

a ? b : c ? d : e is evaluated as a ? b : (c ? d : e)

consider: z = ((a == b ? a : b) ? c : d);

If we try to use left-associate logic, this example would be impossible to execute with some complex made up math we don't care about, instead:

first condition: if (a==b) z=a
second condition: if(b) z = c;
final condition: z=d

If we took the left execution as read, our code would wire like:

`int z, tmp;

if(a == b) tmp = a;
else tmp = b;

if(tmp) z = c;
else z = d;
`
??????
Maybe I'm not too sure, but this doesn't work because we need a made up variable to fill in our logic, so we can consider that imaginary

The idea is that instead of nesting stacks of what amounts to if-else stacks, we simply add conditionals to our operator to execute from our original variable, in this case z.

Ternary Operator Vs. If Else

There is no major difference between runtime big O memory allocation between a ternary and a well written if/else(as I have seen evidence for). There is some debate to which style is faster, or more readable. Not up for debate is the fact that the Ternary operator is more professional outside of loops and will bring your code to a higher standard.

 Why not just use an if/else to make things much easier? 
Enter fullscreen mode Exit fullscreen mode

Well, we could nest huge amounts of these conditionals, at a cost. The readability of our code is somewhat subjective, and utilizing the ternary operator is one of the tools in our arsenal to achieve that impossible goal of readable JS.

credit to Chris Lutz: "Why is the conditional operator right associative?"

Top comments (2)

Collapse
 
zmfreecodecamper profile image
Zoran Milic

Good Job Here !

Collapse
 
zmfreecodecamper profile image
Zoran Milic

Too Many Loops Make The Code Very Hard To Understand.