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



<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>
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 ) ;


<do not remove the three backticks above>


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

randonNum is 0
randonNum is 1

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


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


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.


you could also do:

var randomNum = 0;
  do {
        console.log("Print while condition true.");  
    } 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


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.