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.

CODE EXAMPLE 1:

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

CODE EXAMPLE 2:

let cupsOfSugarNeeded = 3
let cupsAdded = 0

do {
  cupsAdded++;
  }
  while (cupsAdded < cupsOfSugarNeeded);  {
  console.log(cupsAdded); 
  };

This is a shortcut you can do in Javascript!

// These two are equivalent
i = i + 1
i++

// The same with this
i = i - 1
i--

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