Why use Math.min and Math.max to create boundaries for an input and not use an if statement?

In the “Build a Library” project we create a parent class, named Media, that has a method for adding ratings, the “.addRating()” method. If we want to make sure input is between 1 and 5, we can use “Math.min(Math.max(number, 1), 5)” or we also can use an “if” statement. So, why use the Math.min and Math.max instead of the if statemet? Is there any advantage?

Thank you!

The example you gave simply forces the value (assuming it is numeric) to be between 1 and 5 inclusive. So if I were to enter 6 as a value, Math.min(Math.max(number, 1), 5) would force it to be 5. You can accomplish the same thing with the following:

if(!isNaN(number) {
   if(number < 1) number = 1;
   if(number >5) number = 5;

There is not necessarily a distinct advantage of one vs the other.

1 Like

Thank you!
Now I understand more about my question.