Method 1: Math.min and Math.max
One of the most straightforward ways to cap a number to a specific range is to use the Math.min and Math.max functions. These functions can be used to limit a number to a specific minimum and maximum value, respectively. Here's an example:
const value = 10; const cappedValue = Math.min(Math.max(value, 0), 100); // limits value to range 0-100
In this example, the Math.max function is used to ensure that the value is at least 0, while the Math.min function is used to ensure that the value is no greater than 100. This approach is simple, easy to read, and works well for most use cases.
Method 2: Ternary Operator
Another approach for capping numbers is to use a ternary operator. This approach can be useful if you want to perform some additional logic based on whether the number is within the range or not. Here's an example:
const value = 10; const cappedValue = value < 0 ? 0 : value > 100 ? 100 : value; // limits value to range 0-100
In this example, the ternary operator checks whether the value is less than 0 or greater than 100, and returns the appropriate value based on the result. This approach can be more concise than the Math.min and Math.max approach, but may be harder to read for some developers.