Why is zero logging to the terminal?


#1

The following...

var num = 10
while(num >= 1) {
    console.log(num);
    num=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?


#2

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
console.log(num)

Now the 0 won't be displayed.


#3

@bbrigance,
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 ==" );


#4

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?


#5

Consider this model:

num = 10;
while (num > 0){
    console.log(num--);
}

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

10
9
8
7
6
5
4
3
2
1

#6

@bbrigance,

OR
did you want

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

#7

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


#8

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