Build library - Step 25 addRating - making sure input is between 1 and 5

Hi all,

I’m struggling for a long time to find the code with the use of Math.min() and Math.max() on this step. For now, I managed to get the result using an if statement, but I would really love to understand how to do using this instead. I’ve been searching the internet for a long time now, but I can’t seem to find a definite solution. Could someone help me with it? I’m supposed to use it using spread syntax and I found this formula but I can’t seem to make it work:

function getMaxOfArray(numArray) {
  return Math.max.apply(null, numArray);

This is how I made step 25 work for now using an If statement (In .addRating() , make sure input is between 1 and 5):

    if(value < 1 || value > 5) {
      console.log('Error! Please rate between 1 and 5')
    } else {

Have you checked MDN Web Docs? If you don’t know what it is, it’s basically a programming Wikipedia.


yes I did. That’s where the function example comes from…

Anybody? It would really help me to understand it :grinning:

Hi @jesveedee,
I think I’ve understood what you’re after, which is the following:

function inRange(value) {
value = Math.min(value, 5);
value = Math.max(value, 1);
return value; }

// returns 5

// returns 1

//returns 3

I haven’t used either of these functions before but what seems a bit counterintuitive to me is that you use Math.min() to create an upper bound (i.e., the function takes the lower of the two input values) and Math.max() to create a lower bound. From MDN:

Math.min() is often used to clip a value so that it is always less than or equal to a boundary.

Does that answer your question?

Edit: I just realised you can do the following, which is a bit more graceful:

function inRange(value) {
let cappedValue = Math.max(Math.min(value, 5), 1);
return cappedValue; }

But it’s a bit more obvious how the first one actually works.

1 Like

Hi @jonrosk089,

Thanks a lot for this! Now I get a better understanding of how to implement this.

This is what Codecademy would like you to use, but it doesn’t do anything in the results. With my if statement I will get an error if the number isn’t between 1 and 5 which is the assignment.

Thanks again!

1 Like