For Loops Practice: Shopping Basket – Hints

If you’re working on the Shopping List Challenge and feeling a bit stuck, here are some hints to get you coding.

The Fish and Lemon Loops

The first loop we need to make is a for loop to add the fish to the shopping basket.

Let’s start by copying in the for loop reference from our review:

Now we have two questions:

  • How many times should we loop?
  • What should happen each time we loop?

Try to answer these questions yourself, then check your answer:

  • We want to loop as many times as we want fish in our basket. We have a global variable, numFish, that holds how many fish to add to the basket. So we want to loop numFish times.
  • Each time we loop we want to add a fish to the basket. We have a function addItemToBasket() that we can call with the string “fish” as the parameter to add a fish to the basket.

Now trying filling in the reference for loop using the answers to those questions!

Check your answer:

Now test it out! Try clicking on the Get New Shopping List button and then the Fill Basket button. Did you get the right number of fish icons in your basket?

Using the fish loop as a reference, can you write the lemon loop?

The Other Items Loop

Now we need a for-of loop to add the other items to our shopping basket. We’ll add one of each item in the otherItems array.

Let’s start by copying the reference for-of loop to our fillBasket() function

Now we have two questions:

  • What array do we want to loop over?
  • What should happen each time we loop?

Try to answer these questions yourself, then check your answer:

  • We want to loop over the array stored in the global variable otherItems. It has the names of the other items we need to add to our basket.
  • We should add the item we’re currently on to our basket. We can use the addItemToBasket() function and pass in the name of the item from the otherItems array as the parameter. The name of the item we should add each time will be stored in the items variable that our for-of loop created.

Let’s fill in the reference for-of loop!

Check Your Answer:

Test it out! Try clicking on the Get New Shopping List button and then the Fill Basket button. Are you getting all the correct items in your basket?

Leave a Reply

Your email address will not be published. Required fields are marked *