Reputation: 13
(first stackoverflow post) This is a javaScript question, but I think the logic applies anywhere
I've wondered for a long time about using an if statement to compare multiple values against the same variable without needing to type out the variable every time; specifically, in regards to "greater than" and "less than".
The specific example I'm trying to solve is:
var middle = 5;
if(middle < 10 && middle > 0) {
//some stuff
}
I'm looking for something like:
var middle = 5;
if(middle (< 10 && > 0)) {
//the same stuff
}
I have checked is-there-a-way-to-shorten-the-condition-if-it-always-compares-to-the-same-thing and if-statements-matching-multiple-values and if-statement-multiple-conditions-same-statement. I could not derive a simple answer to my specific question from those.
A final note: I do not want to make a new "multiple if" function that accepts arguments and then compares them for the variable. I am looking for a "built-in" way to do this.
Thanks, -Charles
Upvotes: 1
Views: 3653
Reputation: 97
If anyone is doing this in python for multiple values you can try this
exclude = ['10','0','20','30','12','14']
if i not in exclude:
print(i)
Upvotes: 0
Reputation: 69934
I am looking for a "built-in" way to do this.
Javascript doesn' t support this feature. In fact, most languages don't and Python is the only famous example I can think of right now that does that (you can write 0 < middle < 10
there).
In Javascript, the best you can do is use a shorter variable name
if(0 <= x && x < 10)
Or abstract common tests into a function
if(between(0, x, 10))
Upvotes: 0
Reputation: 664307
Some languages like Python and Coffeescript (which compiles to JS!) have chained comparisons:
if (0 < middle < 10)
However, Javascript does not have these. Just as you already do, you will need to reference the variable twice:
if (0 < middle && middle < 10)
Upvotes: 4
Reputation: 9257
Right, don't do this, but just for the sake of it :
if (Math.min(10, Math.max(0, middle)) == middle) {
// middle is between 0 and 10
}
Upvotes: 0
Reputation: 3996
I don't believe it's possible, for a logical operator you need both sides of the operator to evaluate to true or false.
If you are missing a side the statement can't be evaluated.
Upvotes: 1