Do...while loop not working

Hi all,
I have just completed the lesson on Javascript loops and I was playing around to practice with the different loops methods.

I do not understand why the code below would not give me the desired outcome when using the do…while loop.

I would like to select the first 3 items of the array groceryList but when I log on the console I receive brown rice and pasta. (4, 5)

Also, when I change the sign < to >, it creates an infinite loop.

see the below code for reference:

let groceryList = [
  "orange juice",
  "bananas",
  "coffee beans",
  "brown rice",
  "pasta",
  "coconut oil",
  "plantains",
];
// For loop syntax
for (let i = 0; i < 5; i++) {
  //console.log(groceryList[i]);
}
// while loop syntax
let i = 0;
while (i < 2) {
  i++;
  //console.log(groceryList[i]);
}
// do...while loop syntax

do {
  i++;
  console.log(groceryList[i]);
  
} while (i >= 3);

Your printing is beginning with brown rice because you did not fully comment out your first while loop.
The first while loop increments i to 1 and then your do-while loop begins.
Further, you are incrememnting i before you do your first console log which increments it to 2.
Remember that indices in array begin with 0. So brown rice has index 2.

You do not need both a while and a do-while loop to do your algorithm. The while for the do-while comes in the while statement following the do block.

1 Like

Thanks so much for your explanation!

Just cross-checking: does it mean that the do…while loop would work fine if I commented out the first two loops?
it seems yes, still if I declare let i = 0 it would not log the first item of the array

let groceryList = [ "orange juice", "bananas", "coffee beans", "brown rice", "pasta", "coconut oil", "plantains", ]; let i = 0 do { i++; console.log(groceryList[i]); } while (i <= 3);

Once again, I can’ t see why, and just noticed that if I give a value of -1 to i instead that would work

Absolutely the first two loops aren’t needed! and yet the actions on i that are within them are affecting how your do-while loop runs.
Take a look at line 12 and consider what the value of i is at the first time that line 13 gets hit.

The solution is to move i++ from line 12 to line 14.

2 Likes