PDA

View Full Version : Operator logic problem


Tails
12-13-2002, 08:07 PM
Why is it that statements like this don't work.

E=1
Z=2
if (E<Z<4) {alert("something")}

while this statement does

if E<Z &&Z<4){alert("something")}

I'm trying to shorten my scripts a bit.

jkd
12-13-2002, 10:29 PM
The "<" and ">" operators return a boolean.

They also evaluate left to right.

And true typecasts to 1, and false to 0.

Therefore:

1 < 4 < 6

really evaluates to:

(1 < 4) < 6
true < 6
1 < 6
true

whammy
12-13-2002, 11:34 PM
Interesting. I feel dumb now, since I should have figured that out - but that also explains why it doesn't work (although in the case of the example, it should definitely trigger the alert - even if E and Z were switched around...). ;)

brothercake
12-14-2002, 12:31 AM
Interesting indeed. If you apply a different grouping

( 1 < ( 2 < 4 ) )
( 1 < true )
( 1 < 1 )
false


which is consistent with your results. Perhaps this has something to do with implied parenthesisation (!) Our cafe at work had a quiz - work out this sum:

5 + 7 * 10 / 3

And they were expecting the answer to be 40. But of course it isn't, because that expression is actually

5 + (7 * (10/3) )

Which is 28.3 recurring.

Imagine my disdain :(


But I digress ... if the logic in a condition flows left to right, why does it evaluate the way it apparently does I wonder ... ?

whammy
12-14-2002, 12:46 AM
That's a good question - it looks to me like the logic actually flows right to left...

An easy way to fix that (which I'm sure you know) is to use:

alert((5 + 7) * (10/3))

But no matter what happens if you use that in a URL, it also alerts "Access Denied.". What's up with that?!?

Not to mention, if you reverse the order of the calculations, it still returns 28.33333333333333333333333333........... this looks like one of those math problems that I hate. :D

Long live parentheses. ;)

Tails
12-16-2002, 08:16 PM
I tried grouping by parentheses once, but the logic still was false. I haven't tried all the possibilities yet. But if the first set returns 1 for true, then we all know that
1*anything=anything
and
0*anything=0
But I don't think this would shorten the scripts any though. Maybe there is a use for this in another way?

Tails
12-16-2002, 08:21 PM
A newbie posted something about if-else statements and tried multiple < > operators too. It's at

http://www.codingforums.com/showthread.php?threadid=11495