nas5w / javascript-tips-and-tidbits

A continuously-evolving compendium of javascript tips based on common areas of confusion or misunderstanding.
MIT License
1.2k stars 72 forks source link

Suggest using += instead of ++ #26

Open eridal opened 3 years ago

eridal commented 3 years ago

Please consider replacing the increment/decrement operators (++ and --) for their cousins, += and -= respectively.

Even there is no consensus if those operators are good/bad, there are some who believe they are legacy and should be avoided or even removed from the language (eg. python, go)

Here is a quick few reasons that I've seen first-hand when teaching programing 101 at my Uni:

1) they have a complex side-effect, which is not intuitive to newcomers: like the readme explains, i++ and ++i means two different things and their post-conditions are entirely different to each other.

2) at a glance they seem to break from parenthesis, which again could be surprising for the newcomers, like for instance a=(i++) will still produce the value previously to be incremented

3) they are poorly defined at grammar level, for instance (i)++ works, which should not, but even if that works then why (a, i)++ wont?

4) they break the right-to-left expected order of operations, for instance compare a = b += 1 with a = ++b


Honestly using += 1 is not too much of a trouble than ++ and certainly helps to avoid some pitfalls plus at the same time it makes the development environment more inclusive and easy for everybody to precisely understand what is the original author intended.

Please don't write clever code, be clever writing code that everybody can understand!