3. For or while


#1

Does anyone know why sometimes, I get two answer on the screen? For example here is my code for this example:

x = 5;
while(x){
console.log(x);
x = 0;
}

and it returns a 5 and a 0? shouldn't it just return 5 because the 0 means false here and it is just stop the loop?


#2

positive integers (1 and larger) are considered true, zero is false. So on your first line you declare:

x = 5;

so on you second line, the condition is true. then you third line it will print x (5), then you make x false (0), now it is at the end of the loop, so it will go check the condition of the loop again. the condition is false, so the loop ends. So the loop has executed once, make sense?


#3

@stetim94 - I understand what is going on with the code but I don't understand why I get both 5 and 0 on the screen. Shouldn't I only see a 5?


#4

In trying to test this for myself in the console, I crashed my browser a few times. . .

Anyway, it just seems to be the nature of the while loop. What you can be sure is not happening is that the values are literally being returned. The result of the last variable value which the loop ends on is simply being logged to the console.


#5

i think that is codecademy, causing the zero to print. If i run this code on jsbin (link) or outside of codecademy on my own computer, it only shows 5, not zero


#6

It's not about codecademy but about the console. What happens is that any value that occurs in the code is buffered until it is either used or replaced and if the code is terminated with a value in the buffer e.g. this statement has a value of 0:

x = 0;

then this is echoed to the console. As @emgo_dev almost mentioned that is not a real output and effects only the last value in the code.

@stetim in your case you're not using any console but write to the page instead so you don't see this feature, but if you run it in the webconsole of your browser you should see this as well.