0

Despite working with JavaScript for quite a while now I've only recently started reading up about operator precedence, however I've stumbled across a bit of a wall which I can't seem to find an answer for.

Consider the following example:

x=1;      // x === 1
x++;      // x === 2

x=1;      // x === 1
y=x++;    // x === 2, y === 1

If ++ has a higher precedence than =, how is y not becoming 2?

Now consider:

x=1;      // x === 1
y=++x;    // x === 2, y === 2

If ++x and x++ have identical associativity, how come y is becoming 2 in this case?

Here's an accompanying Fiddle.

James Donnelly
  • 122,518
  • 33
  • 200
  • 204

4 Answers4

3

The ++ operator, when it appears after a variable or property reference, is a post-increment operation. That means that the value of the ++ subexpression is the value before the increment.

Thus it's not just operator precedence at work here. Instead, it's the basic semantics of the operator.

When ++ appears before the variable or property reference, it's a pre-increment. That means that the value of the subexpression is the already-incremented value of the variable or property.

Pre- and post-increment was part of the C programming language, and maybe one or more earlier languages. Some computer instruction sets have addressing modes with behaviors that are reminiscent of the effect of pre- and post-increment.

Pointy
  • 389,373
  • 58
  • 564
  • 602
2

x++ is a post-increment. It returns the current value of x and then increments it by one. ++x, on the other hand, is a pre-increment. It increments the value of x by 1 and then returns the current value of x.

Blender
  • 275,078
  • 51
  • 420
  • 480
1

Putting the ++ after the variable performs a postfix incrementation. The variable is incremented, but the old value is returned in the expression.

Putting the ++ before the variable is a prefix incrementation. The incremented value is returned. This has nothing to do with operator precedence.

Further reading

Mike Christensen
  • 82,887
  • 49
  • 201
  • 310
0

This is because ++x and x++ are not the same.

  • ++x increments x and returns the new value
  • x++ increments x and returns the original value
gen_Eric
  • 214,658
  • 40
  • 293
  • 332