Skip to main content

clamp()

clamp(value, min, max): number

Clamps a value between min and max bounds.


Parametersโ€‹

value: numberโ€‹

Value to clamp.

min: numberโ€‹

Minimum bound (inclusive).

max: numberโ€‹

Maximum bound (inclusive).


Returns: numberโ€‹

The clamped value.


Throwsโ€‹

RangeError If min is greater than max.


Sinceโ€‹

2.0.0


Performanceโ€‹

O(1)


Also known asโ€‹

clamp (Lodash, es-toolkit, Remeda, Radashi, Ramda, Effect, Antfu) ยท โŒ (Modern Dash)


Exampleโ€‹

clamp(5, 0, 10);  // => 5
clamp(-5, 0, 10); // => 0
clamp(15, 0, 10); // => 10

How it works?โ€‹

Restricts a value to stay within a specified range. If below min, returns min. If above max, returns max. Otherwise, returns the value unchanged.

Visual Rangeโ€‹


Use Casesโ€‹

Restrict value range ๐Ÿ“Œโ€‹

Constrain a number between a minimum and maximum value. Essential for UI sliders, physical limits, or color values.

const opacity = clamp(inputOpacity, 0, 1);
element.style.opacity = String(opacity);
console.log(`Applied opacity: ${opacity}`);

Normalize geometric boundsโ€‹

Ensure coordinates stay within the screen or map boundaries. Perfect for game development or canvas rendering.

const x = clamp(player.x, 0, screenWidth);
const y = clamp(player.y, 0, screenHeight);

Limit volume or brightness levelsโ€‹

Constrain user-adjustable settings to safe ranges. Essential for accessibility and hardware protection.

const volume = clamp(userVolume, 0, 100);
audioPlayer.setVolume(volume);

Constrain design tokens in a design systemโ€‹

Ensure computed design token values stay within safe bounds. Prevents layout breakage from extreme user preferences or dynamic calculations.

const fontSize = clamp(baseFontSize * userScale, 12, 32);
const spacing = clamp(baseSpacing * density, 4, 48);
const zIndex = clamp(computedZ, 0, 9999);

Enforce premium bounds for insurance calculationsโ€‹

Constrain calculated premiums within regulatory and business limits. Critical for insurance pricing engines ensuring compliance and profitability.

const MIN_PREMIUM = 150;    // Minimum viable premium
const MAX_PREMIUM = 25000; // Regulatory cap

const calculateAutoInsurance = (driver) => {
// Base premium calculation
let premium = 500;
premium *= driver.age < 25 ? 1.8 : 1.0; // Young driver surcharge
premium *= driver.accidents > 0 ? 1.5 : 1.0; // Accident history
premium *= driver.vehicleValue / 20000; // Vehicle value factor

// Clamp to regulatory and business bounds
return clamp(premium, MIN_PREMIUM, MAX_PREMIUM);
};

// Examples:
calculateAutoInsurance({ age: 22, accidents: 2, vehicleValue: 45000 });
// Calculated: 6075 => clamped to 6075 (within bounds)

calculateAutoInsurance({ age: 65, accidents: 0, vehicleValue: 8000 });
// Calculated: 100 => clamped to 150 (minimum premium)