Skip to content Skip to sidebar Skip to footer

Why Does This `do`–`while` Loop Repeat The Last Value After The End?

I tried the following code in the Google Chrome console and I’m getting this output. Why is there an additional 4 printed? Output: 0 1 2 3 4 4

Solution 1:

There is no extra 4 at end. Your loop is correct and works just fine :). That's return value of the i++ expression, which you are mistaking for console.log in developer console. Try this, you will figure it out;

var i=0;do{console.log('i = ', i);i++;}while(i<5);

Edit Thanks to @ggorlen for pointing this out, it's the return value of last expression in block({}) which is i++, i increments the value and returns it's last value (if i = 4; i++ returns 4 and makes value of i = 5), (++i, returns 5 and makes value of i = 5)

var i=0;do{console.log('i = ', i);++i;}while(i<5);

will give return value of 5

Solution 2:

JavaScript has the concept of "Completion Records". Basically every statement produces a completion record.

The Completion type is a Record used to explain the runtime propagation of values and control flow such as the behaviour of statements (break, continue, return and throw) that perform nonlocal transfers of control.

You usually cannot do anything with these in user land code, but the runtime needs those to properly execute your program. However the Chrome console will print the value of the completion record of the last statement it executes.

Without going into to much details, here is what happens:


The simplest example to demonstrate this behavior is simply

42;

The result of evaluating this expression statement is a completion record that looks something like

{
  type:normal,
  value:42,
  target:empty
}

You will see it print 42 in the console because that's the value of the completion record of the expression statement.

A slightly more evolved example:

if (true) {
  42;
}

will print the same.

Solution 3:

Yeah, it's normal that extra 4. It's called expression evaluation. Id doesn't mean it's printing, but instead evaluating i to you.

Check here to know more about it.

This is just chrome helping you to know the dynamic environment of your variables.

Post a Comment for "Why Does This `do`–`while` Loop Repeat The Last Value After The End?"