user5102448
user5102448

Reputation:

How to write a conditional that checks if a variable falls within a range of values?

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

Answers (2)

Bathsheba
Bathsheba

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

James Donnelly
James Donnelly

Reputation: 128791

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

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

Upvotes: 3

Related Questions