skip to Main Content

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.

2

Answers


  1. The prefix operator ++i increments then outputs the variable, and the postfix operator i++ outputs then increments the variable.

    For the prefix code, ++i outputs the value of i itself after incrementing, so i never reaches 5.

    It outputs 1, 2, 3, 4. The first one is 1 because i gets incremented from 0.

    For the postfix code, i++ outputs a value of the incremented i smaller by one, so even if i had reached 5 by i++ing, it actually outputs 4. Because of the outputted 4 being smaller than 5, the final statement gets executed.

    The value of i by the last statement execution is 5, so 5 gets printed at last.

    By that, the output is 1, 2, 3, 4, 5.

    Then the i++ will print 5 for i = 6 so the execution gets stopped.

    Postfix example:

    let i = 4;
    alert(i);    // 4
    alert(i++);  // 4, even though i is now 5
    alert(i);    // 5
    alert(i++);  // 5, even though i is now 6
    alert(i);    // 6
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search