Confused about the postfix increment operator and assignment operator precedence in JavaScript

Viewed 66

The operator precedence documentation says that the postfix increment operator have a higher precedence over the assignment operator, but the following example shows that the opposite is true:

var i = 1;

var j = i++;

console.log(j);  // will output 1 (I expected the output to be 2)

Why the output is 1 instead of 2?

1 Answers

The post-increment operator increments the value of the variable, but returns the value before it was incremented. Therefore, j will have a value of 1 while i will have a value of 2.

var i = 1;
var j = i++;
console.log("j =", j);
console.log("i =", i);

See increment operator:

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.

Related