alternative if syntax

D

dsmithy

Hi,
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 ? " " : "*";

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 "*". But (i * j) % 8 isn't a
conditional. It just evaluates to a number. So how is the choice made
between " " and "*"?

Thank you,
 
R

rf

dsmithy said:
Hi,
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 ? " " : "*";

This is not an if statement.
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 "*". But (i * j) % 8 isn't a
conditional. It just evaluates to a number.

Correct. And for numbers 0 is false and anything else is true.
 
D

dsmithy

This is not an if statement.

Well, the "if" keyword certainly isn't present, but the author of the
book I'm reading does refer to this construction as an "alternative
if" syntax.
Correct. And for numbers 0 is false and anything else is true.

Aha! You're right. I didn't make the connection with type conversions.
Thank you for your helpful reply.
 
T

Thomas 'PointedEars' Lahn

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 product of
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 `+='.
Thank you,

You're welcome, but please read the FAQ now, and ultimately RTFM.

<http://jibbering.com/faq/#posting>


PointedEars
 
T

Thomas 'PointedEars' Lahn

dsmithy said:
Well, the "if" keyword certainly isn't present, but the author of the
book I'm reading does refer to this construction as an "alternative
if" syntax.

Sounds like just another bad book. Dump it.
Aha! You're right.

They are not.
I didn't make the connection with type conversions.

Although that is probably one of the first thing a book on ECMAScript
scripting should teach. The number of people asking why "1" + 2 === "12"
being a telltale sign of that.
Thank you for your helpful reply.

Hmmm.


PointedEars
 
T

Thomas 'PointedEars' Lahn

Thomas said:
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'.

It is the other way around, of course:

(±)`0' and `NaN' are converted to _false_, and all other values to _true_.

Sorry for causing confusion.


PointedEars, saying goodnight
 
D

dsmithy

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 `+='.
Thank you,

You're welcome, but please read the FAQ now, and ultimately RTFM.

<http://jibbering.com/faq/#posting>

PointedEars

Well you're a testy one, aren't you. I've been "RTFM" as you so
crudely put it and trying to understand (in truth I feel like I've
figured out quite a bit on my own without bugging the likes of you). I
read about type conversions (the book I'm reading did present it early
on) but I just didn't make the connection between that concept and the
conditional operator -- I guess we can't all be as quick or smart as
you apparently are. When you don't have the time to take a course with
a teacher, it's really nice to have a resource like this group to
bounce the occasional question off of and get it immediately resolved.
Sorry to have wasted your time with my "easy" question. Then again,
judging by the amount of spam clogging up this group, I'd say that
right there's your *real* problem...
 
S

Stevo

Thomas said:
That is _not_ "alternative if syntax". See below.
PointedEars

Yes it is. There's nothing at all wrong with referring to a ternary
statement as "alternative if syntax". It gets across in very simple
terms what you can do with it. If a regular if looks like this:

if ( x==1 ) y=2; else y=0;

and as a ternary statement it looks like this:

y = x==1 ? 2 : 0;

That is clearly an alternative if syntax. Stop trying to confuse people.
 
S

Stevo

dsmithy said:
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]

PointedEars

Well you're a testy one, aren't you. I've been "RTFM" as you so
crudely put it and trying to understand (in truth I feel like I've
figured out quite a bit on my own without bugging the likes of you). I
read about type conversions (the book I'm reading did present it early
on) but I just didn't make the connection between that concept and the
conditional operator -- I guess we can't all be as quick or smart as
you apparently are. When you don't have the time to take a course with
a teacher, it's really nice to have a resource like this group to
bounce the occasional question off of and get it immediately resolved.
Sorry to have wasted your time with my "easy" question. Then again,
judging by the amount of spam clogging up this group, I'd say that
right there's your *real* problem...

It doesn't take long for people to figure out how unfriendly PointedEars
is. It's weird isn't it, if he only knew how to communicate in a
friendly manner he might well become a hero around here. Instead though,
despite his obvious knowledge, he makes enemies here every day.
 
O

optimistx

Stevo said:
It doesn't take long for people to figure out how unfriendly
PointedEars is. It's weird isn't it, if he only knew how to
communicate in a friendly manner he might well become a hero around
here. Instead though, despite his obvious knowledge, he makes enemies
here every day.

Yes.

When writing a book the publisher provides a person to read the text,
and propose (usually numerous) changes to make it follow certain styles,
habits, rules. With the help of such a person the texts of some people
(not only TL) here would be good material for an educational book.
But with the bitter, sour, unfriendly tone now here (as understood
by readers) might prohibit the sales of a future bestseller.

FAQ is material for the book. It is irrational to call it FAQ, when
frequently asked questions are not allowed here. It would be more
useful as a manual, with pictures, diagrams, friendly human attitude.

Trying to be consice and accurate as scientific text is not educationally
useful. Very few people if any start learning a new science by
reading original research reports.

I share the feelings of the OP. Do not go away.
 
S

SAM

Le 10/20/09 2:53 AM, dsmithy a écrit :
Hi,
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 ? " " : "*";

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)

Yes indeed.

when (i * j) % 8 == 0 ==> false
or when (i * j) % 8 == NaN ==> false
if not ==> true

Try in the address bar :
javascript:alert((1*0)%8);alert((1*0)%8?'ok':'!ok')
javascript:alert((1*'a')%8);alert((1*'a')%8?'ok':'!ok')
javascript:alert((1*2)%8);alert((1*2)%8?'ok':'!ok')
 
G

Gregor Kofler

Stevo meinte:
Yes it is. There's nothing at all wrong with referring to a ternary
statement as "alternative if syntax". It gets across in very simple
terms what you can do with it. If a regular if looks like this:

if ( x==1 ) y=2; else y=0;

and as a ternary statement it looks like this:

y = x==1 ? 2 : 0;

That is clearly an alternative if syntax. Stop trying to confuse people.

It's only an alternative in this very particular case. Hence calling it
an "alternative if syntax" (wich implies "general alternative") is
completely wrong.

Gregor
 
S

Stevo

Gregor said:
Stevo meinte:


It's only an alternative in this very particular case. Hence calling it
an "alternative if syntax" (wich implies "general alternative") is
completely wrong.

Gregor

But as an explanationary description to help out someone learning
JavaScript, it's a perfectly fine description.
 
B

beegee

Gregor Kofler wrote:


But as an explanationary description to help out someone learning
JavaScript, it's a perfectly fine description.

Yes, it's a fine description but one gets the impression that the book
the op read actually calls it "the alternative if syntax" which as
stated by Gregor and Thomas, is wrong. The name in this language and
many others is the ternary statement. Even as a description,
"alternative if-else clause" would be better. I agree with Pointed
Ears. Dump the book.

Also, remembering the order of precedence in a statement like:

res += (i * j) % 8 ? " " : "*";

seems a hellish exercise.

I would write it:

var appendStr = ((i * j) % 8 )? " " : "*";
res += appendStr;


I had a friend who loved to write things like:

return userPrefersRed()?userPrefersMaroon()?
processOrange():
(userPrefersBurgundy()?
processBurgundy():
processRed()):
processBlue();

His code was strangely bulletproof but impossible to read.


Bob
 
T

Thomas 'PointedEars' Lahn

beegee said:
Gregor said:
It's only an alternative in this very particular case. Hence calling it
an "alternative if syntax" (wich implies "general alternative") is
completely wrong.
[...]

But as an explanationary description to help out someone learning
JavaScript, it's a perfectly fine description.

Yes, it's a fine description but one gets the impression that the book
the op read actually calls it "the alternative if syntax" which as
stated by Gregor and Thomas, is wrong. The name in this language and
many others is the ternary statement.

But at least in the languages discussed here (ECMAScript implementations),
the name is _not_ ternary statement, but Conditional Operation.
Even as a description, "alternative if-else clause" would be better.

That still suggests that a statement and an expression would be equivalent,
which they are not.
I agree with Pointed
Ears. Dump the book.

Without the space, please, bee gee ;-)


PointedEars
 
D

dsmithy

Yes, it's a fine description but one gets the impression that the book
the op read actually calls it "the alternative if syntax" which as
stated by Gregor and Thomas, is wrong.

Actually it's my mistake in wording my OP -- I used the definite
article "the", incorrectly assuming that this "alternative" (if we can
call it that!) syntax was the *only* alternative to if. I had no basis
for making such an assumption, and, in fact, the book refers to it as
*an* alternative syntax. Furthermore, the book does refer to the
character ? as the ternary operator (without providing further
elaboration).
Ears.  Dump the book.

The book is called _Object Oriented JavaScript_ by Stoyan Stefanov,
and it's received very favorable reviews on Amazon.com compared to a
lot of the other JavaScript books. I'm not ready to dump it just yet,
but I'm all ears if anyone wants to suggest an alternative. I was
thinking about the books mentioned in the groups FAQ (_JavaScript: The
Definitive Guide_ and _JavaScript The Good Parts_), but I was a bit
concerned they were too advanced for me at this point.
 
S

SAM

Le 10/20/09 3:17 PM, beegee a écrit :
res += (i * j) % 8 ? " " : "*";

seems a hellish exercise.

I would write it:

I do not like write indermediate variables used only for cutting things
var appendStr = ((i * j) % 8 )? " " : "*";
res += appendStr;


I had a friend who loved to write things like:

return userPrefersRed()?userPrefersMaroon()?
processOrange():
(userPrefersBurgundy()?
processBurgundy():
processRed()):
processBlue();

His code was strangely bulletproof but impossible to read.

all depends ...
with this particular example that sound to me quite clear

user prefers maroon ? hop! orange
if not, perhaps does he prefers burgundy? so OK this time
if not (ie: yellow), hop! red
default (no choice) is blue.

javascript:alert(!!i?i==3?'orange':(i==2?'burgun':'red'):'blue');

javascript:i=1;alert(!!i?i==3?'orange':(i==2?'burgun':'red'):'blue');

javascript:i=prompt('1, 2, 3 or nothing/empty');
alert(!!i?i==3?'orange':(i==2?'burgun':'red'):'blue');

there, it was a little more difficult to read but not more than :

var coloriz, i=prompt('1, 2, 3 or nothing/empty');
if(typeof i != 'undefined') {
if(i==3) coloriz = 'orange';
else (
if(i==2) coloriz = 'burgundy';
else coloriz = 'red';
}
}
else coloriz = 'blue';
alert(coloriz);

javascript:i=prompt('cancel or 2, 3, nothing/empty');switch(i){case
'3':i='orange';break;case '2':i='burgundy';break;case
'':i='red';break;default:i='blue'};alert(i)

var i=prompt('cancel or 2, 3, nothing/empty');
switch(i){
case '3': i='orange'; break;
case '2': i='burgundy';break;
case '': i='red'; break;
default: i='blue';
};
alert(i);
 
L

Lasse Reichstein Nielsen

Stevo said:
Yes it is. There's nothing at all wrong with referring to a ternary
statement as "alternative if syntax". It gets across in very simple
terms what you can do with it. If a regular if looks like this:

if ( x==1 ) y=2; else y=0;

and as a ternary statement it looks like this:

"ternary statement"? The typical mistaken name for the "?:" operator
is "the ternary operator", probably caused by taking a clause in the C
programming language specification out of context.
It is technically correct, even the use of "the", since the "?:"
operator is the only ternary operator (i.e., one that takes three
operands) in the C and JavaScript languages, but it's hardly
discriptive.

A better name for an expression built from the "?:" operator is a
"conditional expression". The operator itself is often called the
"conditional operator".

And it is *not* an *alternative* to "if" statements. It's more like a
parallel: "?:" does for expression what "if" does for statements.
y = x==1 ? 2 : 0;

That is clearly an alternative if syntax. Stop trying to confuse people.

No, that's a conditional at the expression level, not at the statement
level. The difference is both significant and important.

You can't use the conditional operator as an alternative in this "if"
statement:
if (test) while(true){} else break;
Nor can it easily represent this statement:
if (test) { x = 42; }
Especially the latter is instructive. When one understands why you can't
directly translate it to using "?:", one has, probably, understood the
fundamental difference between expressions and statements.

The conditional expression is no more an alternative to "if" statements
than the undefined value is an alternative to zero, even if they behave
the same in certain situations (e.g., conversion to boolean).

/L
 
O

Osmo Saarikumpu

optimistx kirjoitti:
I share the feelings of the OP.

What exactly was so "unfriendly" or "crude" as the OP put it? I could
not have responded more civilly even if I had three weeks to practice.
In fact, TL's response was not only civil, but also cordial. Go ahead,
read it, parse it and get the correct returned value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top