Log in

View Full Version : At A Glance Conditionals: Ternary Operators



rainarts
07-26-2008, 01:47 AM
Conditionals: Ternary Operators
Ternary operators are a shorthand if/else block who's syntax can be a bit confusing when you're dealing with OPC (Other People's Code). The syntax boils down to this.

var userName = 'Bob'; var hello = (userName=='Bob') ? 'Hello Bob!' : 'Hello Not Bob!';

In this example the statement to be evaluated is (userName=='Bob'). The question marks ends the statement and begins the conditionals. If UserName is, indeed, Bob then the first block 'Hello Bob!' will be returned and assigned to our hello variable. If userName isn't Bob then the second block ('Hello Not Bob!') is returned and assigned to our hello variable.
In psudeo code...

var someVariable = (condition to test) ? (condition true) : (condition false);

The question mark (?) and colon (:) tend to get lost in complex expressions as you can see in this example taken from wikipedia (but which will also work in Javascript if the various variables are assigned...)

for (i = 0; i < MAX_PATTERNS; i++) c_patterns[i].ShowWindow(m_data.fOn[i] ? SW_SHOW : SW_HIDE);

So while quick and efficient, they do tend to reduce the maintainability/readability of the code.

Dal
07-26-2008, 03:11 AM
Since the Moderators around here are obvously on holiday or something I guess its up to me to let you know that tips and tricks have a section :

http://www.dynamicdrive.com/forums/forumdisplay.php?f=25

Im sure its all good stuff but this board (General Coding > JavaScript) is really just for problems.

Kind Regards
Dal

jscheuer1
07-26-2008, 04:27 AM
The tips and tricks section has a minimum post restriction for creating new threads (the hope being that only accomplished coders will be able to post new threads there). Besides that, I don't think this is a tip, trick, or even a question. But I may have missed something.

rainarts -

Any particular reason why you posted this?

I can tell you that code written that way need not be too confusing, but it depends upon the context, and the readability and clarity of the surrounding code. However, you are correct in most cases. Using branching if (and if needed: else if, and/or else) statements is generally clearer, as can be using the switch method. In fact, if there is only one option (no 'else'), if is best.

rainarts
07-26-2008, 04:45 AM
Wel as you can, am just a newbie here! Don't worry next time im gonna do the right thing... Tnx 4 remindin me... tgc