Skip to main content

JavaScript function to clamp/restrict a number whose value is limited to the given range.

/**
 * Returns a number whose value is limited to the given range.
 *
 * Example: limit the output of this computation to between 0 and 255
 * (x * 255).clamp(0, 255)
 *
 * https://stackoverflow.com/a/11409944
 *
 * @param {Number} min The lower boundary of the output range
 * @param {Number} max The upper boundary of the output range
 * @returns A number in the range [min, max]
 * @type Number
 */
Number.prototype.clamp = function(min, max) {
    return Math.min(Math.max(this, min), max);
};

// no prototype extension
function clamp(current, min, max) {
    return Math.min(Math.max(current, min), max);
}

// https://stackoverflow.com/a/11410079
function clamp(current, min, max) {
    return current <= min ? min : current >= max ? max : current;
}

// https://github.com/30-seconds/30-seconds-of-code/blob/master/snippets/clampNumber.md
function clamp(current, min, max) {
    return Math.max(Math.min(current, Math.max(min, max)), Math.min(min, max));
}