1

Here is an array of donut objects.

var donuts = [
  { type: "Jelly", cost: 1.22 },
  { type: "Chocolate", cost: 2.45 },
  { type: "Cider", cost: 1.59 },
  { type: "Boston Cream", cost: 5.99 }
];

Directions: Use the forEach() method to loop over the array and print out the following donut summaries using console.log.

Jelly donuts cost $1.22 each
Chocolate donuts cost $2.45 each
Cider donuts cost $1.59 each
Boston Cream donuts cost $5.99 each

I wrote this code but it doesn't work :

donuts.forEach(function(donut) {

    console.log(donuts.type + " donuts cost $" + donuts.cost + " each");

});

What's wrong?

3
  • 1
    You should use donut inside console not donuts console.log(donut.type + " donut cost $" + donut.cost + " each") Commented Dec 18, 2018 at 15:33
  • 1
    You are trying to access a property of the entire array instead of the looped item (donuts vs donut) inside the forEach callback. That's why it doesn't work. Commented Dec 18, 2018 at 15:39
  • 2
    Simple typo. Off-topic. Commented Dec 18, 2018 at 15:42

2 Answers 2

4

Instead of

donuts.forEach(function(donut) {

    console.log(donuts.type + " donuts cost $" + donuts.cost + " each");

});

change it to

donuts.forEach(function(donut) {

    console.log(donut.type + " donut cost $" + donut.cost + " each");

});

You are looping through the donuts array and calling each object a donut, but in your code, you are still trying to reference donuts.

Sign up to request clarification or add additional context in comments.

1 Comment

Omg I was so close :) Thank you very much
0

donuts.forEach(function(donut) { console.log(${donut.type} donut costs $${donut.cost} each)

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.