"While" printing last number twice?


#1

j = 1
while (j < 10) {
console.log(j);
j++;
};

This code is printing numbers 1-9 followed by another 9. Why would it print the 9 twice?

Thanks!


While Loops - Output Repeating the Last Result Twice
#2

It had something to do with the console on codecademy, not exactly sure what. If you want to know, i will ask around. Hope this helps


#3

Okay, as long as it's a fluke and I'm not missing something. I just wanted to make sure I properly understood the lesson and wasn't causing an unexpected output as a result of something I did. It passed me on that lesson, so I had no way to know.

Thanks again :slightly_smiling:


Don't Repeat Yourself : Result printing twice
Introduction to 'While' Loops in JS 11 Review
Can anyone explain object in javascript in detail?
19. Review: Built-In Functions. Should it return "None" in the console?
#4

No, you are not missing something. Your code is fine and works as it should


#5

The problem is not the console on codecademy, but that codecademy uses a console. Normally consoles are just for one statement at a time execution. So when you enter a statement like:

question = 42

you get the echo of this value, here: 42
Assuming of course that this has a value as statement e.g.

var name = value
console.log(value)
undefined

have no value or are at least not shown this way. And that feature seem to apply to many consoles, the web consoles and the shell act similar to this. One explanation that I've heard (no idea if it is that way), was that every value is stored in a 1 value buffer until it is either used in a statement or replaced by the next value and when the program terminates (whether it is a statement or a script) this buffer is emptied to the output.

So long story short what you see in the console by the second nine is the value of this statement:
j++;

And as @stetim94 already said it is not harmful, in fact it could be useful if you want to see a value but are too lazy to use console.log. And it is also the reason why you can see a returned value from a function on the console, although not using console.log and although return does not print to the console. But as the console in real life is more a debugging tool for javaScript and the output is probably made explicitly by a function you probably better get used to using a function e.g. console.log to get an output instead of the console.

Hope this helps.


14. A Quick Question
Help on Python