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);
};
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.