Why is a 1 generated for my "while" loop?


#1

var hotDog = 0

for(i=0; i<5; i++){
console.log("This is a for loop");
};

while(hotDog<2){
console.log("This is a while loop");
hotDog++
};

It outputs the correct number of times, but it leaves 1 number less than the number of times the condition is true below the statements. So in this case a 1, if I put 10 in the while, I get 9.


#2

I'm not really sure I understand your question, but your control flow says

while hotDog is less than number, print to console.log, add one to hotDog afterwards.

It will start at 0 (since you set hotDog = 0). And you state you don't want to print anything after hotDog becomes 10 or greater.

Were you trying to do the following instead?

for(i=0; i<5; i++){
console.log("This is a for loop");
};

while(hotDog<2){
hotDog++
console.log("This is a while loop");
};

#3

Ok, so if I set hotDog++ after the console.log it prints out 1 less than the number of true statements, a literal '1'.

This flow fixes the issue though, which means the program reads the execution of the loop "hotDog++" and then runs the console log, rather than the previous running a statement of when the statement ends being true separate from the console.log.
If I put
while(hotDog<=2){
console.log("This is a while loop");
hotDog++
};

I would get 2 at the end instead of 1

Thanks!


#4

The problem is that the exercises are run in a console and as most consoles this means that you get a quick echo of your input (unless it is undefined). So when you enter e.g. 2+2 you'll see 4 in the console even without using console.log explicitly. For longer code this will only echo the last unused value. Don't know if this is true but one intuition was that it buffers the current value until it is either used or replaced and the last value in the buffer when the program end will be displayed on the screen.

So in your case hotDog++ has a a value of hotDog which is 1 at the time and due to this statement becomes 2, therefore you see the 1. But when you swap it with console.log you don't see anything because console.log uses it's input value but has no value of its own for example console.log(console.log()) reveals undefined.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.