Luketep
Luketep

Reputation: 181

Javascript (-1 <= 5 <= 1) === true?

I want to validate that a given number is within a given range:

function validate(min, max, amount) {
    return (min <= amount <= max);
}

But this does not seem to work properly. I know I can do it with two comparison and a logical AND, but I would like to it in one comparison. Is there any NATIVE javascript way to realize this?

Upvotes: 4

Views: 143

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382160

Use this instead :

return (min <= amount && amount <= max);

There is no shortcut. And there is a good reason the JavaScript engine can't guess your intent : what you typed was valid, it just isn't interpreted as you'd like. You were testing, in fact

((min <= amount) <= max)

and the result of the first comparison, which is a boolean, is converted to 0 or 1 for the second one (more details here about operators precedence, those comparison operators are left-to-right).

If you really want a shortcut, you could do this :

Number.prototype.isin = function(m,M) {
   return m<=this && this<=M; 
};

console.log(0.5.isin(1,2)); // logs false
console.log(3..isin(2,5));  // logs true

but I personally would use the standard solution with && that everybody can read and which doesn't involve an additional function call.

Aside : I could have called my function in instead of isin but it might break ES3 browsers.

Upvotes: 9

Igor S.
Igor S.

Reputation: 3350

Operators ( == , <= , < , >= , == ) take only 2 arguments.

When there are more arguments it uses mathematical order of computing. So in fact your code behave like:

min <= amount  // true
true <= max // this is illogical

It's also optimal, because when executing logical statements and finding something like:

if(false && (some computing))

It will ignore (some computing) because result will be always false

This is very common practive in every language. Test like this will not have NullPointerException error, because first argument is already false.

if(obj != null && obj.getValue() > 10) //C++,Java, etc.

if(obj !== undefined && obj.val() > 10) // javascript
if(obj.length != 0 && obj.val() > 10) //jQuery

Upvotes: 3

Related Questions