Use Math.min and Math.max to keep a value inside a range.

math-clamp JavaScript does not have a built-in `clamp` function, but `Math.max` and `Math.min` can combine to keep a value between two limits.

Math Clamp

score
math_clamp.js
Replay: real traced execution (multi-file project)
const score = 12;
const low = 0;
const high = 10;
const clamped = Math.min(high, Math.max(low, score));

console.log("score=" + score);
console.log("clamped=" + clamped);
const score = -3;
const low = 0;
const high = 10;
const clamped = Math.min(high, Math.max(low, score));

console.log("score=" + score);
console.log("clamped=" + clamped);
const score = 7;
const low = 0;
const high = 10;
const clamped = Math.min(high, Math.max(low, score));

console.log("score=" + score);
console.log("clamped=" + clamped);
  1. score ← 12, low ← 0, high ← 10, clamped ← 10

    1const score→ 12 = 12; //@score=-3, 72const low→ 0 = 0;3const high→ 10 = 10;4const clamped→ 10 = Math.min(high10, Math.max(low0, score12));56console.log("score=" + score12);7console.log("clamped=" + clamped10);
    outputscore=12
    clamped=10
  1. score ← -3, low ← 0, high ← 10, clamped ← 0

    1const score→ -3 = -3;2const low→ 0 = 0;3const high→ 10 = 10;4const clamped→ 0 = Math.min(high10, Math.max(low0, score-3));56console.log("score=" + score-3);7console.log("clamped=" + clamped0);
    outputscore=-3
    clamped=0
  1. score ← 7, low ← 0, high ← 10, clamped ← 7

    1const score→ 7 = 7;2const low→ 0 = 0;3const high→ 10 = 10;4const clamped→ 7 = Math.min(high10, Math.max(low0, score7));56console.log("score=" + score7);7console.log("clamped=" + clamped7);
    outputscore=7
    clamped=7