skip to Main Content

Is there a version of the += operator that post-increments?

I understand pre- and post- increment in JS (++i and i++), and I also am aware of i += n if I want to increment by n, but to my understanding the += operator is a pre-increment. If I want to do an inline post-increment by more than 1, which operator would I use? Is this possible?

Currently, my approach is to simply increment the variable on another line, but doing this inline would be nice!

2

Answers


  1. += operator is pre-increment by default.
    A quick use of console.log tells that,

    let i=0;
    console.log(i++);  // 0 (post-increment)
    console.log(i);    // 1
    console.log(++i);  // 2 (pre-increment)
    console.log(i+=1); // 3 (pre-increment)
    Login or Signup to reply.
  2. The general solution for post-increment (i++-style behavior, where the expression evaluates to the original value of i, then i is incremented after) can, and should, be to perform the increment on a separate line. Both post-increment (i++) and pre-increment (++i) are essentially convenience features that create confusion (as your initially confused question made clear; you mixed up the terms). Any time the distinction between them is relevant (when they’re not standing alone, outside larger expressions), it’s likely to create confusion, so trying to find more ways to achieve these effects with decidedly non-standard workarounds is asking for trouble.

    You can do silly tricks like:

    i+=j,i-j
    

    (though that will fail unless parenthesized in basically every scenario) or:

    [i,i+=j][0]  // Or [i,i+=j].shift()
    

    which is safer in larger expressions since it doesn’t have precedence issues, and doesn’t need to repeat the operand twice, at the cost of creating and discarding a two-element array (I’d hope the JIT compiler can convert that to the efficient form, but who knows?), but it’s pointless. Just perform your larger expression, then add i+=j after.

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