Problem #1: Write a while loop that prints out each item of ingredients.
Problem #2: Write a for loop that does the same thing.
Problem #3: Write any loop, while or for, that prints out each item of ingredients but backwards (that is, the first should be "bananas" and the last "eggs").
What am I missing?
const ingredients = [
"eggs",
"milk",
"flour",
"sugar",
"baking soda",
"baking powder",
"chocolate chips",
"bananas"
];
let i = 0;
while (i < ingredients.length) {
console.log(ingredients[i]);
i++;
}
for (let i = 0; i < ingredients.length; i++);
console.log(ingredients);
for (let i = 0; i < ingredients.length; i++);
console.log(ingredients.reverse());
As you follow your console output, you will understand what is wrong there. From what I understand from your code, you are not looping through the array in your last two loops. Instead, you are directly outputting the array. Also, think about how you can reverse each element of the array using a loop. Your first loop shows promise in solving this.
Additionally, your loops need to follow this syntax, with the loop code enclosed within curly braces.
for (let i =0; i < ingredients.length; i++) {
...
}
That is why you only gives 10 console output insteed of 24.
You can’t end the loop with ; if you want to log on the next line. As long as the next line is only a single line you do not need the loop code block, but I would really encourage you not to write loops like that and always have the code block.
The second loop is not using the index in the log
The third is cheating (also the ; is still wrong). You are supposed to loop backward. You can reverse the logic of the loop (init the start index to the length - 1 and decrement the index as long as it is greater than or equal to 0)