How to check if a number is between two values?
In JavaScript, I'm telling the browser to do something if the window size is greater than 500px. I do it like so:
if (windowsize > 500) {
// do this
}
This works great, but I would like to apply this same method, but with a range of numbers. So I would like to tell my browser to do stuff if the window size is between 500px and 600px. I know this wouldn't work, but here is how I imagined it:
if (windowsize > 500-600) {
// do this
}
Is this even possible, within JavaScript?
Tests whether windowsize
is greater than 500
and lesser than 600
meaning that neither values 500
or 600
itself will result in the condition becoming true.
if (windowsize > 500 && windowsize < 600) {
// ...
}
I had a moment, so, although you've already accepted an answer, I thought I'd contribute the following:
Number.prototype.between = function(a, b) {
var min = Math.min.apply(Math, [a, b]),
max = Math.max.apply(Math, [a, b]);
return this > min && this < max;
};
var windowSize = 550;
console.log(windowSize.between(500, 600));
JS Fiddle demo.
Or, if you'd prefer to have the option to check a number is in the defined range including the end-points:
Number.prototype.between = function(a, b, inclusive) {
var min = Math.min.apply(Math, [a, b]),
max = Math.max.apply(Math, [a, b]);
return inclusive ? this >= min && this <= max : this > min && this < max;
};
var windowSize = 500;
console.log(windowSize.between(500, 603, true));
JS Fiddle demo.
Edited to add a minor amendment to the above, given that – as noted in the comments –
…
Function.prototype.apply()
is slow! Besides calling it when you have a fixed amount of arguments is pointless…
it was worth removing the use of Function.prototype.apply()
, which yields the amended versions of the above methods, firstly without the 'inclusive' option:
Number.prototype.between = function(a, b) {
var min = Math.min(a, b),
max = Math.max(a, b);
return this > min && this < max;
};
var windowSize = 550;
console.log(windowSize.between(500, 600));
JS Fiddle demo.
And with the 'inclusive' option:
Number.prototype.between = function(a, b, inclusive) {
var min = Math.min(a, b),
max = Math.max(a, b);
return inclusive ? this >= min && this <= max : this > min && this < max;
}
var windowSize = 500;
console.log(windowSize.between(500, 603, true));
JS Fiddle demo.
References:
-
Function.prototype.apply()
. -
Math.max()
. -
Math.min()
.
I prefer to put the variable on the inside to give an extra hint that the code is validating my variable is between a range values
if (500 < size && size < 600) { doStuff(); }