Re: [flexcoders] Quick Question: Conditional Operator ?:

2007-02-28 Thread Troy Gilbert

The difference you point out is the only difference.

The trinary operator (?:) is an operator so it can be used in expressions
(it evaluates to something). if/else is control flow and thus does not
evaluate to anything nor can it be used inside of an expression.

For certain situations, it can make the code easier to read and more compact
than a control flow statement. It could possibly make the generated code
faster if only because the byte code is simpler or more compact (more cache
coherent). But I can't imagine it'd make a huge difference.

Personally, I prefer it for the situations you mentioned... whenever I see
if x return y else return z I always think, could this be more concisely
written with the trinary operator?

The place I most often use it, though, is in initialization of variables
passed into function parameters, e.g. this.x = (x) ? x : 0; will set
this.x to x if x is valid (not null, not undefined) otherwise it'll set it
to zero. I'm sure its not an accident that it almost reads like a sentence
with a question mark... ;-)

Troy.


On 2/27/07, camlinaeizerous [EMAIL PROTECTED] wrote:


  I know using ?: does the same thing as if else but is there an actual
benefit of one over the other besides a difference in typing a few
characters? Not that I would go through all my code an chance one to
the other just curious if someone knows.

something really simple for example

return (a==b)?Yes:No

vs

if(a==b)
{return Yes}
else
{return No}

 



[flexcoders] Quick Question: Conditional Operator ?:

2007-02-27 Thread camlinaeizerous
I know using ?: does the same thing as if else but is there an actual
benefit of one over the other besides a difference in typing a few
characters? Not that I would go through all my code an chance one to
the other just curious if someone knows.

something really simple for example

return (a==b)?Yes:No

vs

if(a==b)
{return Yes}
else
{return No}