I was experimenting with a simple do while loop in JS, and it gave me unexpected results. I wonder if someone might explain why it does what it does?
Here’s the code:
var y = 0;
do {
console.log(y);
y -= 1;
} while (y > 0);
My expectation was that on the first iteration, it would print out the value of y (namely, 0), decrement y, then notice that y is not greater than 0 (-1 is less than 0, as some elementary school teacher taught me long ago) and stop. So I should get 0 printed to my console and nothing else.
Actual results?
0
-1
Why? How is it getting to -1? And, having gotten to -1, why does it stop there?
@Jatudrei, note that the console has the same behaviour, namely that it shows the last variable evaluated. Just check this by running x=0;, which will show 0 (at least in FF console).
@rmdawson71, no problem. I’m not offended, I understand that you didn’t know from my username whether I’m a man or a woman and you didn’t want to assume. So I informed you–sorry if I came across as indignant; that was not my intention.
@BenGitter, yeah, I see that you’re right. I tried the same thing, but with console.log changed to alert, like thus:
do {
alert(y);
y -= 1;
} while (y >0);
If your explanation is right, I should get an alert window with the value “0” printed, and still see “-1” appear in the console.
Good. We were concerned you might be a bunch of kids standing on each others’ shoulders in an overcoat trying to pass as an adult. That’s been happening a lot in fCC lately. But seriously…
Yeah, I get the same as you (Jatudrei) when I put it directly in the console. But notice that the -1 has a different prompt. Like someone suggested, I don’t think that’s output from the console.log but is just telling us the last status of the variable. I’m still new to typing directly into the console, so I’m guessing here.
> var y = 0;
do {
console.log(y);
y -= 1;
} while (y > 0);
0
<- -1
This is my attempt to recreate what I’m seeing. Notice the extra prompt in front of the -1.