Prints out more than it should? Help clarify 10/11


#1



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


I set a value to my variable. When the loop runs, I understand that 'do' first prints out the string in my code, then the while kicks in. But in the while loop, the variable randomNum++ would increase in value by one. Given my example code. shouldn't this print only two times instead of three? When I set the varaible greater than 2, the loops prints once and then stops.

Is it printing 3 times because despite randomNum = 0, the 'do' is executed first because it is true from the start of the loop, then the while pulls/reads the randomNum and starts the loop again? I feel like I answered my own question. But someone let me know.


var getToDaChoppa = function(){
  // Write your do/while loop here!
  var randomNum = 0;
  
  do {
        console.log("Print while condition true.");  
    } while (randomNum++ < 2 ) ;
};

getToDaChoppa();


#2

Because the comparison is done before increasing the randomNum. So, it will print:

do
randonNum is 0
randonNum is 1

if you would do ++randomNum, there will be two printouts


#3

Ahh ok, reread and do/while loops runs at least once. Now I see why I get the extra line.


#4

Thank you, stetim94. I never thought of doing ++randomNum. Not enough coding experience from my end. But with your advice now, it'll surely stick to me.


#5

you could also do:

var randomNum = 0;
  
  do {
        console.log("Print while condition true.");  
        randomNum++;
    } while (randomNum < 2 ) ;

this will result in two printout outs, one for the do part of the loop. Then random number gets increased to 1, 1 is smaller then 2, so the loop will run again. And 2 < 2 is false, so the loop will exit after the second run


#6

Ahh that's nice too. But given the difference variations, wouldn't the first code you provided earlier be considered cleaner? ... After thinking about it, I thought it wouldn't make sense to have randomNum++ in the 'do' section, but I see why you could if the 'while' condition was something totally different then what's used in this exercise. Cool!! Thanks again.