Here is an array of donut objects.
JavaScript
x
7
1
var donuts = [
2
{ type: "Jelly", cost: 1.22 },
3
{ type: "Chocolate", cost: 2.45 },
4
{ type: "Cider", cost: 1.59 },
5
{ type: "Boston Cream", cost: 5.99 }
6
];
7
Directions: Use the forEach() method to loop over the array and print out the following donut summaries using console.log.
JavaScript
1
5
1
Jelly donuts cost $1.22 each
2
Chocolate donuts cost $2.45 each
3
Cider donuts cost $1.59 each
4
Boston Cream donuts cost $5.99 each
5
I wrote this code but it doesn’t work :
JavaScript
1
6
1
donuts.forEach(function(donut) {
2
3
console.log(donuts.type + " donuts cost $" + donuts.cost + " each");
4
5
});
6
What’s wrong?
Advertisement
Answer
Instead of
JavaScript
1
6
1
donuts.forEach(function(donut) {
2
3
console.log(donuts.type + " donuts cost $" + donuts.cost + " each");
4
5
});
6
change it to
JavaScript
1
6
1
donuts.forEach(function(donut) {
2
3
console.log(donut.type + " donut cost $" + donut.cost + " each");
4
5
});
6
You are looping through the donuts
array and calling each object a donut
, but in your code, you are still trying to reference donuts
.