Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Clamp a Number

Numbers, Dates & Timerseasy

Course · Section 12: Numbers, Dates, Intl and Timers · Lecture 182: Math and Rounding

Implement `clampNum(n, lo, hi)` returning `n` limited to the range `[lo, hi]`.

Sample tests

Input: clampNum(5, 0, 10)
Output: 5
Input: clampNum(-1, 0, 10)
Output: 0

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Applying the bounds in the wrong order when they are close.
Approach & explanation (try first)

Math.min(Math.max(n, lo), hi) keeps n within the inclusive range.

Loading...
⌘/Ctrl + Enter

Run your code to see results.