Design & Download
Your JS Library
in Seconds!!!

Snippet: clamp() - Confine Numbers To A Specific Range

Written by Christopher West (cwest) on January 14, 2016.
Use this function to make sure that a given number will always be within a given range.
function clamp(x, min, max) {
  return x < min ? min : x > max ? max : x;

clamp(...) API Documentation

Confine a given number to a specific range.


  1. x {number}:
    The number to be confined to the specified range.
  2. min {number}:
    If this number is greater than x, this number will be returned.
  3. max {number}:
    If this number is less than x, this number will be returned.


Returns the closest number to x that greater than or equal to min and less than or equal to max.