![]() | |
![]() |
| | Thread Tools | Display Modes |
#1
| |||
| |||
|
|
Much appreciated--but I'm still confused as to why that is required. If I can do conditionals in the if...else format without the else statement, why can't I do the same with ?: operator shortcut? |
|
Also, why does it have to be the word *true*--I tried it with just putting anything behind the *:*, like *: var hello = "hello"* for example, and that still causes an error--why is this? |

#2
| |||
| |||
|
|
On Sun, 1 Feb 2004 17:05:41 -0500, TheKeith <no (AT) spam (DOT) com> wrote: [snip] Much appreciated--but I'm still confused as to why that is required. If I can do conditionals in the if...else format without the else statement, why can't I do the same with ?: operator shortcut? It's not a shortcut; it's a ternary operator. Unary operators, like !, require one operand. Binary operators, like +, require two operands. Ternary operators, like ?:, require three. Only using two operands with them is like trying to use: var a = b *; // or a = * b; Also, why does it have to be the word *true*--I tried it with just putting anything behind the *:*, like *: var hello = "hello"* for example, and that still causes an error--why is this? The syntax of the operator is: (expr) ? (if-true expr) : (if-false expr) The first expression is evaluated. If it is considered true, the second operand (if-true expr) is evaluated and returned. If the first expression is considered false, the third operand (if-false expr) is evaluated and returned. The main use for the operator is conditional assignment. Say, for example, you wanted to ensure that an argument in a function is always valid[1]: function a( x ) { x = (undefined == x) ? 0 : x; } a(); Here, no argument was passed to function a(), so the expression (undefined == x) will evaluate to true. This means that the operator, as a whole, will evaluate to 0 and 0 will be assigned to x. a( 6 ); Here, (undefined == x) will evaluate as false because x is 6. The operator, as a whole, will evaluate to 6, so 6 will be assigned to x. If you are just wanted to do perform something based on a certain condition, then just use an if statement. If you want an expression to evaluate to a different value based on a condition, then use the conditional operator. |
![]() |
| Thread Tools | |
| Display Modes | |
| |