I'm currently learning JavaScript on Code Academy and I am at the end of the while loops section.
The following code:
j = 0;
while (j < 3) {
j++;
}
produces a 2 on the console and I have no clue why. I tried running this on Eclipse JaveEE only to realize that using a HTML file with this code as a script gives me a different result: a blank page.
That makes sense to me, because I've only incremented j to 3, but not printed it. Not sure why the CodeAcademy console gives me a 2.
This is a screenshot of the console output:
codeacademy console output
1 Answer 1
The behaviour you're observing is because that's how a browser console works.
For every code you evaluate it tries to return some value. For trivial expressions it's easy - 2 + 2 would presumably return 4.
For code that consists of multiple statements it's much more complicated and console tries to be smart. What adds more complexity into this is the fact that console's behaviour is not standardised, so what we observe at this very moment for a given browser is not guaranteed to hold true for another browser or for another release of the same one.
Let's try to find out what is happening though:
j = 0;
while (j < 3) {
j++;
}
for this code browser tries to be smart and outputs the value of the latest found expression, which is in this case is j++;. It returns 2 because that was the value of j on the last iteration before loop termination. And since the postfix increment returns the current value before modifying it - it returns 2.
If we change it to
j = 0;
while (j < 3) {
++j;
}
the output would be 3, for the very same reason.
Now let's try something different:
j = 0;
while (j < 3) {
j++;
a = 42;
}
this would output 42. Since the a = 42 is the latest expression in this code.
j = 0;
while (j < 3) {
j++;
var a = 42;
}
For this sample it would again return 2, since console decides to ignore the assignment statement and reverts back to the latest expression.
To summarise: this behaviour is not standardised, and browsers just try to be useful and to output something, even if it's not what you expect to be. So my advice would be to not rely on the implicit console output and use the console.log() explicitly in case when you want to get a result.
3 Comments
eval(). Btw, it would be curious to see a corresponding implementation in browsers.
j++is executed, the expression itself is evaluated to 2 because the evaluation of a post-increment operator returns the value of the variable before the increment. After the execution,jis equal to 3, but the evaluation of the last sentence is 2.