0

I am executing the following seemingly straightforward code

var number = 0;
while (number <= 12) {
    console.log(number);
    number = number + 2;  
}

and I am getting different results in the browser and in Node. When I run it in the Firebug(v 2.0.4 ) console on Firefox(v. 32.0.3) the result I get is

0 2 4 6 8 10 12 14

which is not`the result I expected.

In Node, the same code gives me the correct answer which is

0 2 4 6 8 10 12

Is there anything I'm missing regarding the behaviour in the browser???

Thanks in advance.

7
  • 1
    Can't reproduce, Firefox 32. Commented Oct 7, 2014 at 19:35
  • 3
    Could it be that you are seeing 14 0 2 4 6 8 10 12? The 14 seems to be kind of the "result" of the loop (I guess because of the assignment in the loop body). Just like 1 + 1 prints 2. This is in FF 32.0.3. I can't tell yoy why FF is doing that though. Commented Oct 7, 2014 at 19:37
  • Can't reproduce either, outside of what @FelixKling described. Are you sure you're seeing the 14 on the end? Commented Oct 7, 2014 at 19:38
  • 1
    After the loop the console is printing the value of the last evaluated expression, which is number = number + 2. Commented Oct 7, 2014 at 19:38
  • 1
    You can reproduce by copy-pasting the entire code to the JS console, at least in Chrome. Commented Oct 7, 2014 at 19:38

2 Answers 2

2

If you slightly change your code:

CHROME

var number = 0;
while (number <= 12) {
    console.log("z" + number);
    number = number + 2;  
}

z0
z2
z4
z6
z8
z10
z12
14

You'll see that the 14 is not being printed by the loop. Rather, that is the end value of the expression when the loop finishes running and is printed by the console itself.

FIREFOX

while (number <= 12) {
    console.log("z" + number);
    number = number + 2;  
}

14
"z0"
"z2"
"z4"
"z6"
"z8"
"z10"
"z12"

In Firefox, it runs the entire loop, prints the result and then catches up with the console.

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

2 Comments

I have tried it in Firebug and it gives the same results as Chrome. How can I avoid printing out the 14?
Running inside the console? You can't. Run it inside of a page or something.
1

If you run a script in Firebug's console, then it will evaluate the code. So it's evaluating the value of the last number in the while loop (which is now 14) and prints that out. It's actually printing out the value of number 8 times but groups them in 1 print out.

You can see the same effect by just typing in "window" in the command line. It's evaluating it's value and prints it out in the console.

More info can be found in the description to Firebug's command line.

Comments

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.