Categories
JavaScript Answers

How to use JavaScript to limit a number between a min/max value?

Spread the love

Sometimes, we want to use JavaScript to limit a number between a min/max value.

In this article, we’ll look at how to use JavaScript to limit a number between a min/max value.

How to use JavaScript to limit a number between a min/max value?

To use JavaScript to limit a number between a min/max value, we can use the Math.min and Math.max methods.

For instance, we write

const limitNumberWithinRange = (num, min = 1, max = 20) => {
  const parsed = parseInt(num);
  return Math.min(Math.max(parsed, min), max);
};

to define the limitNumberWithinRange function.

In it, we parse num into an integer with parseInt.

Then we call Math.max with parsed and min to return the max between parsed and min.

Then we get the lower number from Math.max(parsed, min) and max with Math.min.

If parsed is less than min, then min is returned.

And if parsed is bigger than max, then max is returned.

Conclusion

To use JavaScript to limit a number between a min/max value, we can use the Math.min and Math.max methods.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.