Varangian
Varangian

Reputation: 23

Extra output from Javascript nested loop

while practicing loop in JS, I wrote following code.

var bool = true;
while(bool) {
  for (var i = 3; i >= 0; i--)
  {
    console.log(i);  
    bool = i;
  }
}
The output I expected was: 3 2 1 0 (1 digit per line)

The output I encounter was: 3 2 1 0 0 (1 digit per line)

My question is - how does the code or environment component produce the extra "0"?

Thank you for your time and help.

The observed result is produced in Chrome (F12 -> console tab) screen shoot from chrome

Also, on code academy's practice setting. And somehow I cannot produce /or observe any result from the "Run code snippet".

UPDATE:

By switching

console.log(i);

and

bool = i;

I got 3 2 1 0 instead.

This would confirm Pointy's answer - no expression, only function call - Thanks again!

Upvotes: 2

Views: 55

Answers (1)

Pointy
Pointy

Reputation: 413826

The last 0 is just the console mechanism telling you the value of the last expression statement evaluated. If you change it:

var bool = true;
while(bool) {
  for (var i = 3; i >= 0; i--)
  {
    console.log(i);  
    bool = i;
  }
}
"hello world";

you'll see hello world instead of the last 0.

Upvotes: 3

Related Questions