Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 712
Luketep Avatar asked Dec 16 '22 10:12

Luketep


1 Answers

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.

like image 114
Denys Séguret Avatar answered Jan 13 '23 18:01

Denys Séguret