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.

3
  • stackoverflow.com/a/16526692/139010 Commented May 23, 2013 at 21:12
  • 1
    Do you know why this is called the post fix increment operator? That's why. Commented May 23, 2013 at 21:13
  • 1
    This must have been a really tough question since only people with 10,000+ rep answered it! Commented May 23, 2013 at 21:21

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, everything makes so much more sense now! Thanks for the fast response.
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.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.