How does a do...while loop log to the console?

So, I am currently learning the do…while loops. (Exercise: https://www.codecademy.com/courses/introduction-to-javascript/lessons/loops/exercises/do-while-statement)
This is my code:

let cupsOfSugarNeeded = 3;

let cupsAdded = 0;

do {

  cupsAdded++;

  console.log(cupsAdded); 

} while (cupsAdded < cupsOfSugarNeeded) {

}

The problem is that when I add console.log to the “do” part of the loop it prints 1, 2 and 3 as it should. But when I put it in the “while” part, it just prints 3. Shouldn’t it print 1, 2 and 3 as well?

I think when you put the console.log in the do…while loop it will loop until cupsAdded<cupsOfSugarNeeded becomes false. So it prints 3 times.

When you put the console.log at the end of the while it’s not part of the loop thus you end up with just the ending value of the loop.

const cupsOfSugarNeeded = 3; let cupsAdded = 0; do { cupsAdded++; console.log(`I've added ${cupsAdded} cups of sugar so far.`) } while (cupsAdded < cupsOfSugarNeeded){ console.log("Hello."); console.log("The code in this block runs independently from the loop.\nThe looped code is inside the 'do' block.\nPutting curly braces around this code is inconsequential\nunless you define a block scoped variable inside the block.\nThe variable won't be accessible outside of the block."); } { console.log("Same with this block."); const blah = 10; } //Uncommenting the next line will throw a reference error since blah is not defined in this scope //console.log(blah);
while (cupsAdded < cupsOfSugarNeeded) {
  // this code block is not part of the loop
}

The correct syntax is,

do {
    // code
} while (condition)

We can write any code we like inside a freestanding code block, with zero effect.

{
    console.log("this will log; the statement is inline code")
}
// same as

console.log("this will log; the statement is inline code")

Thank you all so much for your help. I got it now :slight_smile:

2 Likes