switz
switz

Reputation: 25188

What is the best way to check >= and <= in Javascript?

I have a number.

I then have an if statement that I want to go like this:

if (5 <= variable <= 10)

So if the number is between 5 and 10, the statement should be true.

What's the best way to go about this?

Thanks.

Upvotes: 0

Views: 128

Answers (4)

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

It is my understanding that at the first conditional false, it stops the checking and moves to the next statement.

Given that, you should examine the most often false condition and put it first.

if ((variable >= 5) && (variable <= 10))

if it is more likely to be less than 4 or

if ((variable <= 10) && (variable >= 5))

if the failure of 10 or greater is more likely to occur.

Upvotes: 0

guilin 桂林
guilin 桂林

Reputation: 17422

Actually, if ( 5>= variable >= 10 ) means if(false) if you means variable between 5, 10 it should be 5 <= variable <=10, and in javascript, the best convention is const value at left, which is from c language if (v=1), if (1=v) problem. so the best is:

if (5 <= variable && 10 >= variable) {

Upvotes: 0

Zack Bloom
Zack Bloom

Reputation: 8417

if ((variable >= 5) && (variable <= 10)) works.

If you do this frequently, consider defining a bounds function:

function inBounds(value, min, max){ return ((value >= min) && (value <= max)); }

Upvotes: 4

nonopolarity
nonopolarity

Reputation: 151036

it is

if (5 <= variable && variable <= 10)

Upvotes: 8

Related Questions