Why is zero logging to the terminal?


The following...

var num = 10
while(num >= 1) {

prints zero to the terminal, but zero is not greater than or equal to one. I can run the same script in ruby, albeit ruby syntax, and it does not print zero. Whats up with that?


When num reaches 0 it no longer meets with the condition so the loop terminates. The program terminates as well.

Consider a terminal and CPU environment. Commands are given at the command line and the CPU executes the command and returns a response. We are working in a console envrionment very similar to this. When we submit our code it is entered at the command line and executed immediately. When it is finished executing the console responds.

When the last command is console.log() then what it outputs is the final response. When the last command is an assignment (num = num - 1) the response will be the value in the assignment (think of the response as a buffer dump). Hence, since your code ends with an assignment, the value 0 is the response.

We can get around this unexpected output by reversing the order of the lines in your while statement.

num -= 1

Now the 0 won't be displayed.


Following the advice of @mtf
you would then have to start with
var num=11;

and as extention

It is the Javascript interpreter which is running in this course-environment,
it display's the last non-displayed action...

You will also encounter this, when you are doing a return-statement
as last action...
You could counter this by using a
console.log( " " ); as last statement....

In some sections of this course, the course-checker Display's data
this you could then identify by placing two EXTRA code-line's:
console.log( "== My End ==" );
console.log( "== All that is displayed now, is the course-checker ==" );


Thanks @mtf and @leonhard.wettengmx.n-

So if I add console.log("=My End="); after the counter, it eliminates that last 0 w/o having to change my start point and still logging 10..1?

edit: So I played around with it. I see what you are saying @leonhard.wettengmx.n- I tried the variations you commented. Just for my own ocd, is there a way not count the zero, AND avoid spaces between logged numbers?


Consider this model:

num = 10;
while (num > 0){

The above uses a postfix decrementer directly in the log out. Postfix decrements after the number is outputed.




did you want

var num = 10;
while( true ) {
   var result = "";
   for ( var i = num ; i>=1 ; i--) {
       result += i;
   console.log( result);


This is more in line with how my thought process works. Thanks.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.