When to use i++ vs ++i vs i+=1

When to use i++ vs ++i vs i+=1

Along with “Hello World” it seems like one of the early things people stumble upon is prefix (++i), postfix (i++), and += (additional assignment) operator notation. These operators can be great tools but unfortunately they can also be a gun to shoot yourself in the foot if you don’t know how they work!

Newer languages like Rust and Ruby support the “additional assignment” (+=) operator, they do not support prefix/postfix operations like i++ or ++i due to the implicit functions they perform. While they may be convenient to use they are also very prone to creating bugs.

Note: Ill be speaking primarily from my experience with languages like JavaScript/TypeScript, C++, Ruby, and Rust.

Postfix (i++) and Prefix (++i)

The most common example of the 3 operations is the postfix operation “i++” as its commonly used when introducing people to for loops in JavaScript:

for (let i = 0; i < 3; i++) {
    console.log(i);
}
This will log: 0, 1, 2

++ in this case will increment the value of i by 1. The reason the first number printed is 0 is because with postfix notation the ++ is after the i and the loop will run first and then perform the increment operation.

Prefix on the other hand will evaluate the operation before the for loop runs:

for (let i = 0; i < 3; ++i) {
    console.log(i);
}
This will log: 1, 2

We see that we increment the variable i before entering the loop which results in the loop only running twice instead of 3 times, something you would only know if you were reading very closely.

While this may work as expected and you may even see it used in many places you should probably use i+=1 in place of i++.

Additional Assignment (+=, -=, etc)

Referred to more commonly as “plus equals” the additional assignment operator simplifies i = i + 1; into i+=1;. While these functionally perform the same action there are some benefits to the latter:

  • languages like Go, Rust, Ruby, etc do no support the prefix/postfix and as they become more popular it becomes more and more likely that your reviewers are less familiar with this syntax
  • +=1 is explicit that your incrementing by 1
  • some web frameworks can behave unexpectedly when mutating state with prefix/postfix operator vs additional assignment (look up how yours behaves)

Conclusion

While you may be a rockstar programmer that never would make a mistake, you will eventually work with developers more junior then yourself and its your responsibility to make your code as readable and explicit as you can for their sake.

I hope this article was helpful for some folks out there, if you want to learn more dev tips please checkout my other posts here!