Strange behavior in #11. Review


#1

I did not get any error messages and the system says everything is good and has passed me along to the next lesson, but I noticed something strange in the output. Here's my code:

// WHILE LOOP
var a = 0;
while(a<5) {
    console.log("While loop # " + a);
    a++;
}

// FOR LOOP
for (var i=0; i<5; i++) {
    console.log("For loop # " + i);
}

// DO-WHILE LOOP
var b = 0;
do {
    console.log("Do-while loop # " + b);
    b++;
} while(b<5);

When my for function is last, it outputs:

While loop # 0
While loop # 1
While loop # 2
While loop # 3
While loop # 4
Do-while loop # 0
Do-while loop # 1
Do-while loop # 2
Do-while loop # 3
Do-while loop # 4
For loop # 0
For loop # 1
For loop # 2
For loop # 3
For loop # 4

But when my for function is not last, it outputs:

While loop # 0
While loop # 1
While loop # 2
While loop # 3
While loop # 4
For loop # 0
For loop # 1
For loop # 2
For loop # 3
For loop # 4
Do-while loop # 0
Do-while loop # 1
Do-while loop # 2
Do-while loop # 3
Do-while loop # 4
4

I have no idea where that extra bit of output is coming from. I even commented out the for loop, and then commented out the other loops. For some reason, that extra 4 does not show up for the for loop but does for the others.


#2

The last 'command' seen by the CPU is b++. When it reaches 4 it has capped out and exits the loop. The value 4 is still in the buffer and is given as the final response.

This is an artefact of working in a terminal environment. Our code is entered in the command line when we submit, and the natural behavior is to give a response once execution is complete. Making our last 'command' (statement in a program)

console.log()

will prevent this output, since logging is the final response.

console.log("Do-while loop # " + b++);

#3

I see. So what you're saying is that even if we don't tell it to, and unless we tell it not to, JS will always output the value of the last thing in the buffer?

I suppose this accounts for similar behavior in Dragonslayer #1, where it always outputs false at the end.


#4

Once we understand the root cause, we can ignore it. Unfortunately this is not well known and many, many learners get confused by it. Nothing we can do, besides fashion our code to output last.


#5

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