Postfix vs Prefix in JavaScript: Why console.log(x++ + ++y) Returns unexpected – JavaScript Increment Operators Explained. Asked in Infosys.

Postfix vs Prefix in JavaScript: Why console.log(x++ + ++y) Returns unexpected – JavaScript Increment Operators Explained. Asked in Infosys.

Our Javascript Code :-

let x = 1;
let y = 2; console.log(x++ + ++y);

1. Initial state

x === 1
y === 2

2. The expression: x++ + ++y

JavaScript evaluates binary operators left‑to‑right, so:

  1. Evaluate the left operand: x++
  2. Evaluate the right operand: ++y
  3. Add the two results
  4. Print the sum


2.1. Left operand: x++ (postfix increment)

  • Postfix means:

    1. Read the current value of x (which is 1).
    2. Then increment x by 1.

  • So the left side contributes 1 to the addition, and after reading it, x becomes 2.


2.2. Right operand: ++y (prefix increment)

  • Prefix means:

    1. First increment y by 1.
    2. Then read the new value of y.
  • So the right side contributes 3 to the addition, and y is now 3.

3. The addition and final result

Putting it together:

  • Left operand gave 1
  • Right operand gave 3
  • Sum: 1 + 3 = 4

console.log(4); // prints 4

✔ Final Answer:

C) 4

This question appeared in the Infosys 1st round of interview, testing the candidate’s knowledge of Pre and Post Increment Operator in JavaScript.

Post a Comment

Previous Post Next Post