Introduction to 'While' Loops in JS - Do / while loop doesn't print text string on final loop


#1


Hi all - Can someone help me understand why the problem below happens on the below excersise?


https://www.codecademy.com/courses/javascript-beginner-en-ASGIv/2/4?curriculum_id=506324b3a7dffd00020bf661#


The loops should count up and down in increments of 5 along with a string of text.
The three loops all work except that the do / while loop does not include the text string with the final number. It just says '50' rather than 'The number 50'.


for (x=1; x<50; x+=5) {
    console.log("The number " + x);
}

var y = 50
while (y>1) {
    console.log("The number " + y);
    y-=5;
}

var z = 0;
do {
    console.log("The number " + z);
    z+=5;
}

while(z<50);


#2

Did you try,

do {

} while (z <= 50);

?


#3

Just tried that, but unfortunately it produces the same result. :frowning2:


#4

Had a typo, fixed now. <=. My apologies.


#5

Your do while loop is written to go up to fifty, i.e. it will stop at printing at 45 unless you change it to be <51 or <=50.

As to why the console shows 50 at the end, my guess is that it's related to what @jibblyj wrote here.

Regarding that link, I believe your console shows 50 because after printing your string the program adds 5 one last time before it checks whether z<50; what I think can be a bit confusing is were you to have incremented by 1 instead of a number > 1 you would never have reached the destination number (i.e. your program would have returned 49 instead of50`), but I digress.

Does that help explain things a bit?

frisby