Clamp a number between a min and max in JavaScript
Beginner · 3 min read
A volume slider goes from 0 to 100. A shop's quantity box goes from 1 to 10. A list of pages goes from 1 to 12. Whenever a number must stay inside a range, you clamp it: a value that is too big is pulled down to the top of the range, and a value that is too small is pushed up to the bottom.
In this tutorial you will write clamp(n, low, high) in one line using Math.min and Math.max, then see what goes wrong when the bounds are passed the wrong way round, and write a safer clampChecked. You need to know what a function is and what Math.min and Math.max do.
The rule, in plain words
- If
nis belowlow, the answer islow. - If
nis abovehigh, the answer ishigh. - Otherwise, the answer is
nitself.
You could write that with if statements. There is a shorter way that uses two functions you already know.
Math.max as a floor, Math.min as a ceiling
Math.max(n, low) can never be smaller than low. If n is too small, low wins:
console.log(Math.max(-20, 0)); // 0
console.log(Math.max(42, 0)); // 42
Math.min(n, high) can never be bigger than high. If n is too big, high wins:
console.log(Math.min(130, 100)); // 100
console.log(Math.min(42, 100)); // 42
Use one to stop the value going too low, and the other to stop it going too high.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
55 Clamp a value into a range
easyWrite clamp(n, low, high) that pulls a number back into a range: a volume slider, a page number, a quantity field. Then find out what happens when the bounds are the wrong way round.
Stuck? Three hints, smallest first
- 1. Two calls, nested: push up to the low bound, then pull down to the high one.
- 2.
Math.min(Math.max(n, low), high)is the whole implementation. - 3. Feed it
clamp(5, 10, 0)and decide whether the answer is acceptable.
Step 1: nest the two calls
Push the value up to low first, then pull the result down to high:
const clamp = (n, low, high) => Math.min(Math.max(n, low), high);
console.log(clamp(130, 0, 100)); // 100
console.log(clamp(-20, 0, 100)); // 0
console.log(clamp(42, 0, 100)); // 42
console.log(clamp(0, 0, 100)); // 0
console.log(clamp(100, 0, 100)); // 100
console.log(clamp(99, 1, 12)); // 12
Read it from the inside out: Math.max(n, low) handles values that are too small, and Math.min(..., high) handles values that are too big. The bounds themselves are allowed. The last line is a page number clamped to the 12 pages that exist.
Step 2: swap the bounds by mistake
What if someone writes clamp(5, 10, 0), with low and high the wrong way round? Work through it:
const clamp = (n, low, high) => Math.min(Math.max(n, low), high);
console.log(Math.max(5, 10)); // 10
console.log(Math.min(10, 0)); // 0
console.log(clamp(5, 10, 0)); // 0
Nothing throws. The answer is 0, the third argument, and it would be 0 whatever n was. If the bounds ever come from a settings file or a user, a silent wrong answer like this is hard to track down.
Step 3: refuse a range that makes no sense
The safer version checks the bounds first and throws a RangeError, the built-in error for "this value is outside what I accept":
const clamp = (n, low, high) => Math.min(Math.max(n, low), high);
function clampChecked(n, low, high) {
if (low > high) throw new RangeError('low ' + low + ' is above high ' + high);
return clamp(n, low, high);
}
console.log(clampChecked(130, 0, 100)); // 100
try {
clampChecked(5, 10, 0);
} catch (err) {
console.log(err.message); // low 10 is above high 0
}
try runs the code, and catch receives the error if one is thrown. The message says exactly what was wrong.
Step 4: NaN slips straight through
NaN ("Not a Number") comes from failed math, such as turning the text 'lagos' into a number. Clamp it and you still get NaN:
const clamp = (n, low, high) => Math.min(Math.max(n, low), high);
console.log(clamp(NaN, 0, 100)); // NaN
Math.max and Math.min give NaN as soon as any value is NaN. A clamp is often the last thing a value passes through before it reaches the screen, so check Number.isNaN on the input there too, rather than trusting the clamp to clean it.
The full solution
The answer panel has clamp and clampChecked, clamps three volume levels, shows the swapped-bounds result and the refusal message. The checks cover the bounds themselves, NaN and a page number. Press Run to see the output.
const clamp = (n, low, high) => Math.min(Math.max(n, low), high);
// The strict version refuses a range that makes no sense.
function clampChecked(n, low, high) {
if (low > high) throw new RangeError('low ' + low + ' is above high ' + high);
return clamp(n, low, high);
}
console.log('volume 130 ->', clamp(130, 0, 100));
console.log('volume -20 ->', clamp(-20, 0, 100));
console.log('volume 42 ->', clamp(42, 0, 100));
console.log('bounds swapped by mistake: clamp(5, 10, 0) ->', clamp(5, 10, 0));
let refused = '';
try { clampChecked(5, 10, 0); } catch (err) { refused = err.message; }
console.log('refused:', refused);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('above the range', clamp(130, 0, 100), 100);
test('below the range', clamp(-20, 0, 100), 0);
test('inside it, untouched', clamp(42, 0, 100), 42);
test('the bounds themselves are allowed', [clamp(0, 0, 100), clamp(100, 0, 100)], [0, 100]);
test('swapped bounds give the LOW argument, silently', clamp(5, 10, 0), 0);
test('so the checked version refuses instead', refused.includes('is above high'), true);
test('NaN survives clamping', Number.isNaN(clamp(NaN, 0, 100)), true);
test('a page number, clamped to what exists', clamp(99, 1, 12), 12);
The interesting case is clamp(5, 10, 0). Nothing throws; Math.max(5, 10) is 10, then Math.min(10, 0) is 0, so a value that was inside neither bound comes back as the high argument. If low and high can ever arrive from user input or a config file, validate them — a silent wrong answer costs more to find than an exception.
NaN passes straight through, because every comparison against NaN is false. A clamp is often the last line of defence before a value reaches a UI, so guard the input's type there rather than assuming the range check cleaned it.
Common mistakes
- Swapping
Math.minandMath.max.Math.max(Math.min(n, low), high)giveshighfor every ordinary number. Remember:maxwithlow,minwithhigh. - Passing the bounds the wrong way round.
clamp(5, 10, 0)answers 0 without any error. Use the checked version when the bounds aren't fixed in your code. - Assuming a clamp cleans bad input.
NaNpasses straight through.
Try it yourself
- Write
clampVolume(n)that usesclampwith 0 and 100 fixed. - Make "next page" and "previous page" buttons that use
clampso the page never goes below 1 or above 12. - Change
clampCheckedso it also throws whennisNaN.