How to check if a number is between two values?

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(); }

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().

Tags:

Javascript