Reputation:
I want to test whether a variable is equal to another variable, or within +5 or -5 that other variable. What's the most succinct way to write this?
if(foo === bar || foo === bar + 5 || foo === bar - 5) { // do stuff };
Not only is this long but it won't evaluate to true if foo = bar + 4, or bar + 3 etc.
Upvotes: 0
Views: 81
Reputation: 234715
if (Math.abs(foo - bar) <= 5)
tells you if foo
and bar
are within 5 of each other.
You see this frequently when comparing equality subject to linear tolerance.
Upvotes: 3
Reputation: 128791
You can do this using Relational Operators (>
, >=
, <
and <=
):
if (foo <= bar + 5 && foo >= bar - 5)
Upvotes: 3