javascriptincrementpost-increment

Incrementing using prefix and postfix


Can someone explain why the alert still shows 5 under postfix? I understand prefix identifies the last iteration to be falsy, but with postfix, it will still return i as 5.

// Prefix Code:
let i = 0;
while (++i < 5) {
    alert(i);
}
// Postfix code:
let i = 0;
while (i++ < 5) {
    alert(i);
}

There are different outputs. With prefix, the output is 1, 2, 3, 4

With postfix, the output is 1, 2, 3, 4, 5

I'm unable to understand why the postfix output will return 5.


Solution

  • Read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment

    If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.

    If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.

    So in the postfix the comparison in the while condition is done with 4 but the value in that alert is 5