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.
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.