Restrict a number to a range

This is JS syntax of the AS3 bound() function I use for my flash projects.

function bound(_number, _min, _max){
	return Math.max(Math.min(_number, _max), _min);

The function takes 3 parametes:

_number is the number you want to restrict.

_min is the minimal value.

_max is the maximum value.

If the _number is less than _min, the function returns the _min value. If the _number is greater than _max, the function returns _max value. This is a way to ensure you number will be within this minimum and maximum bounds.


console.log(boundrary(10,5,15));   // returns 10
console.log(boundrary(2,5,15));    // returns 5
console.log(boundrary(100,5,15));  // returns 15

[highlight]Update: 14 aug 2013 [/highlight]

The snippet is can be found at javascriptcookbook website:

Leave a Reply