Do...while loops

Hi everyone,

In the two code examples below, both of do...while loops, I’m not sure why in code example 1 the do was countString = countString + i; and it the code example 2 it was simply cupsAdded++;. I tried cupsAdded = cupsAdded++ and I think this produced an infinite loop because the screen froze every time I tried to run it!! I just don’t understand why there’s a difference.


let countString = '';
let i = 0;
do {
  countString = countString + i;
} while (i < 5);


let cupsOfSugarNeeded = 3
let cupsAdded = 0

do {
  while (cupsAdded < cupsOfSugarNeeded);  {

This is a shortcut you can do in Javascript!

// These two are equivalent
i = i + 1

// The same with this
i = i - 1

Are you following the JavaScript course? It should be covered in the mathematical assignment operators part

Thanks for you reply! I was aware of the short cut but I don’t know why the full version didn’t work in the practice session? :slight_smile:

The above doesn’t work, but this would, cupsAdded = ++cupsAdded;.

The difference is the order in which the operations are carried out. In the code you tried, you use the post-increment operator, so first the the variable on the left of the = is assigned the value on the right, then the value on the right is incremented. The assignment, however, has already been made, so the incremented value is not stored.

In the second example using the pre-increment operator (++cupsAdded), the value is incremented first, then the variable on the left of the = is assigned to that value, so the desired result is achieved.

As @irlfede pointed out, and you’ve seen from the lesson, there is no need to include = in the process. cupsAdded++ is all that is needed.

Thank you! It makes sense to me now! :slight_smile: :slight_smile:

1 Like