Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Clamp a Number

Fundamentals: Part 1easy

Course · Section 2: JavaScript Fundamentals – Part 1 · Lecture 13: Basic Operators

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

Sample tests

Input: clamp(5, 0, 10)
Output: 5
Input: clamp(-3, 0, 10)
Output: 0

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Applying min before max can give the wrong result if the bounds cross.

Learning resources

  • MDN: Expressions and operators
Visualize this concept: Operator Precedence and Associativity →
Approach & explanation (try first)

Math.min(Math.max(n, lo), hi) first lifts n to at least lo, then caps it at hi.

Loading...
⌘/Ctrl + Enter

Run your code to see results.