dsmithy said:
I came across this line of code in a book. It appears to use the
alternative if syntax, but it doesn't quite make sense to me:
res += (i * j) % 8 ? " " : "*";
That is _not_ "alternative if syntax". See below.
where res is a string variable, and i and j are number variables (i
increments from 1 to 7 and j increments from 1 to 15).
What's confusing me is that I thought the expression preceding the ?
had to be a conditional (i.e., true or false) statement in order for
the computer to choose between " " and "*".
You were mistaken.
But (i * j) % 8 isn't a conditional. It just evaluates to a number.
Exactly.
So how is the choice made between " " and "*"?
ECMAScript implementations until including that of Edition 3 (so all that
are relevant client-side to date) use loose typing. Operators and methods
implicitly convert operands and arguments to values of defined types for
internal processing. With the Conditional Operator, the
/ConditionalExpression/ is evaluated and converted to Boolean. If converted
to `true', the result is " ", otherwise "*":
,-[ECMAScript Language Specification, Edition 3 Final]
|
| 11.12 Conditional Operator (?
|
| [...]
| The production
|
| ConditionalExpression :
| LogicalORExpression ? AssignmentExpression : AssignmentExpression
|
| is evaluated as follows:
|
| 1. Evaluate LogicalORExpression.
| 2. Call GetValue(Result(1)).
| 3. Call ToBoolean(Result(2)).
| 4. If Result(3) is false, go to step 8.
| 5. Evaluate the first AssignmentExpression.
| 6. Call GetValue(Result(5)).
| 7. Return Result(6).
| 8. Evaluate the second AssignmentExpression.
| 9. Call GetValue(Result(8)).
| 10. Return Result(9).
To make a long story short, Number values are converted to Boolean so that
(±)`0' and `NaN' are converted to `true', and all other values to `false'.
This means in your case -- (i * j) % 8 ? " " : "*" -- that if the productof
the values of `i' and `j' is divisible without remainder by 8 (or, IOW, the
product of the values is a multiple of 8), and so the remainder is 0, the
converted value is `false', and the result of the Conditional Operation is
"*"; in all other cases the converted value is `true', and the result is
" ". (This is somewhat counter-intuitive. Human intuition suggests that a
division without remainder to be a success, that should result in `true';
however, the result of the `%' [modulo] operation is not the success status
of the division without remainder, but the remainder itself.)
However, if `res' is a string variable, you might want to consider using
another operator than `+='.
You're welcome, but please read the FAQ now, and ultimately RTFM.
<
http://jibbering.com/faq/#posting>
PointedEars