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

I want to confirm that this number is in the given range:

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

But this does not work properly. I know that I can do this with two comparisons and a logical AND, but I would like to do this in one comparison. Is there any way to implement JavaScript for JavaScript?

+4
source share
2 answers

Use this instead:

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

There is no shortcut. And there is a good reason why the JavaScript engine cannot guess your intentions: what you typed, really, it just is not interpreted as you would like. You actually tested

 ((min <= amount) <= max) 

and the result of the first comparison, which is logical, is converted to 0 or 1 for the second ( more about operator priorities here , these comparison operators are from left to right).

If you really need a shortcut, you can 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 a standard solution with && , which everyone could read and which does not require an additional function call.

Also: I could call my in function instead of isin , but that could break ES3 browsers.

+9
source

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

When there are more arguments, it uses the mathematical order of calculations. So in fact your code behaves like:

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

It is also optimal , because when executing logical instructions and searching for something like:

 if(false && (some computing)) 

It ignores (some computing) , because the result will always be false

This is very common in all languages. A test like this will not have a NullPointerException error, because the first argument is already invalid.

 if(obj != null && obj.getValue() > 10) //C++,Java, etc. if(obj !== undefined && obj.val() > 10) // javascript if(obj.length != 0 && obj.val() > 10) //jQuery 
+3
source

Source: https://habr.com/ru/post/1483110/


All Articles