I'm pretty sure that the following behaves incorrectly (at least, in my mind) because of some truthiness craziness:
var x = 5;
0 < x < 10 // True, and returns true.
0 < x < 2 // False, and returns true.
0 < x < 0 // False, and returns false.
The way I figure it, the (0 < 5) is evaluating to true, and (true < 2) is also evaluating to true (i.e., 1 < 2). I tested this with the third statement, which seems to confirm my theory. Now to the question: is there any way to make this 'work' without large amounts of extra code?
I'm pretty sure that the following behaves incorrectly (at least, in my mind) because of some truthiness craziness:
var x = 5;
0 < x < 10 // True, and returns true.
0 < x < 2 // False, and returns true.
0 < x < 0 // False, and returns false.
The way I figure it, the (0 < 5) is evaluating to true, and (true < 2) is also evaluating to true (i.e., 1 < 2). I tested this with the third statement, which seems to confirm my theory. Now to the question: is there any way to make this 'work' without large amounts of extra code?
Share Improve this question edited Feb 16, 2012 at 21:08 Casey asked Feb 16, 2012 at 21:02 CaseyCasey 1685 silver badges10 bronze badges 3-
If you are using this in a conditional statement, why not use
0 < x && x < 2
? – David Xia Commented Feb 16, 2012 at 21:05 - 1 Three people in less than a minute ... well, I guess I can safely award myself the 'dumb question asked' achievement. – Casey Commented Feb 16, 2012 at 21:07
- as am not i am said use the && to join parisons together instead of chaining them like that. The 2nd one returns true because 5 > 0 evaluates to true, and then through javascript funkiness that lets you pare a boolean and a number, true < 2 and hence the whole thing returns true. – Ameer Commented Feb 16, 2012 at 21:07
3 Answers
Reset to default 10"...is there any way to make this 'work' without large amounts of extra code?"
Sure, use &&
...
(0 < x) && (x < 10)
You can drop the parentheses if you want.
The problem stems from the fact that < is a binary operator.
Which means that one of the < gets evaluated at a time, not both.
Which means that regardless of the order in which they are evaluated (which, IIRC is L to R), one of the parisons will be wrong.
Because this is CODE.
Not ALGEBRA.
Otherwise, clever use of the && operator, as discussed by other answers, will make short work of your problem.
As you have noticed most programming languages will not implement "between" as you would write it mathematically. Instead separate the parisons into two, where only two elements are pared each time.
var x = 5;
0 < x && x < 10
0 < x && x < 2
0 < x && x < 2
So, the first line reads "zero is less than x and x is less than ten". If you are uncertain about in which order the expression will be evaluated, will work as grouping.
(0 < x) && (x < 10)