2

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!

4
  • 1
    I get 3 2 1 0. Are you running this directly in the console? Commented Oct 16, 2015 at 21:14
  • 1
    The output I get is as you expect, in node and in the 'Run code snippet' in your very question. You're doing something different than you show here. Commented Oct 16, 2015 at 21:14
  • @j08691 me too in Chrome Commented Oct 16, 2015 at 21:23
  • @JulianFondren try it in Node from the prompt - that is, just run Node and then paste the code into the terminal/command prompt. Commented Oct 16, 2015 at 21:25

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

7 Comments

what, the bool = i? which environment echoes that?
@JulianFondren Firebug, for one, and the Chrome console also, and Node.js too. It's clear that the OP is doing something similar.
OK, you're citing all of those as behaving as you describe with your code, here, and assuming some similar extra is present in what the questioner is actually doing. That's cool. Just making sure that the value of bool = i is not what would be shown.
@JulianFondren The value of bool=i is definitely what's being shown in those environments.
True :p Also, I pasted the entire code as a single body into node on the command line, rather than run it as a script, and it did display 0 as an extra line of output. I am corrected. But node, what shameful behavior!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.