I wanted to share this dead-simple yet very useful JavaScript snippet I created, with which you can make sure an integer stays within a certain minimum and maximum value. It takes three values (all integers): integer to check, minimum and maximum, and returns the integer to check, corrected to the limits if needed (when it falls out of min/max range).

JavaScript code

function valBetween(v, min, max) {
    return (Math.min(max, Math.max(min, v)));

Click here to try the code in a Fiddle.

View/fork on Github: https://gist.github.com/c-kick/1dfcdc91334a7de3a7af


valBetween(800, 0, 1000); Would output 800
valBetween(80, 0, 20); Would output 20
valBetween(-180, -100, -20); Would output -100

PS: Function can easily be translated to PHP:

PHP code

function valBetween($val, $min, $max) {
    return (min($max, max($min, $val)));

Update dec 3 2014: As Maciej points out in the comments, this is an alternate, potentially faster method (see tests at http://jsperf.com/between-min-max). Though the tests do not give a clear winner, as the results vary greatly on each run.

I was primarily going for super simple code, but I’ll provide Maciej’s code as an alternative:

function valBetweenAlt(v, min, max) {
    if (val > min) {
        if (val < max) {
            return val;
        } else return max;
    } else return min;

And minified:

function valBetweenAltMin(v, min, max) {
      return (val > min) ? ((val < max) ? val : max) : min;