0

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Other guy was first but this might be more succinct for what I have to use this for. Will test :o
Interesting solution. Ran a JSPerf and this is only marginally slower than using relational operators.
3

You can do this using Relational Operators (>, >=, < and <=):

if (foo <= bar + 5 && foo >= bar - 5)

2 Comments

facepalm Of course. But that's not right. You need && not the double pipes. Otherwise that conditional you've written will evaluate to virtually any value. if(foo >= bar -5 && foo <= bar + 5) { // }
@Gaweyne oops. Changed that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.