I tried the following code in the Google Chrome console and I’m getting this output. Why is there an additional 4 printed?
var i = 0;
do{
console.log(i);
i++;
} while(i < 5);
Output:
0
1
2
3
4
4
I tried the following code in the Google Chrome console and I’m getting this output. Why is there an additional 4 printed?
var i = 0;
do{
console.log(i);
i++;
} while(i < 5);
Output:
0
1
2
3
4
4
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
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:
do...while
loop is the value of the completion record of its body.i++;
). The value of the completion record of an expression is the value the expression evaluates to.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.