|
Helping ordinary people create extraordinary websites! |
Essential Javascript -- A Javascript TutorialBy Patrick Hunlock2007-12-02
JavaScript 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'; 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++) So while quick and efficient, they do tend to reduce the maintainability/readability of the code. Tutorial Pages: » Essential Javascript -- A Javascript Tutorial » Getting Started » In-Line Javascript » External Javascript » Javascript is case sensitive » Output (writeln) » Output (alert) » Output (getElementById) » Input (One Click To Rule Them All) » Input (User Input) » Javascript is an Event Driven Language » Comments » Variables » Variable Scope » Special Keywords » Arithmetic Operators » Logical and Comparison Operators » JavaScript Conditionals: IF » JavaScript Conditionals: SWITCH » JavaScript Conditionals: Shorthand Assignment » JavaScript Conditionals: Ternary Operators » JavaScript Loops: FOR » JavaScript Loops: FOR/IN » JavaScript Loops: WHILE » Bringing It All Together » DHTML: Dynamic HTML » Conclusion copyright © 2006, 2007 by Patrick Hunlock |
|