The "unexpected ++" error in jslint [duplicate]
The longstanding best practice:Use i += 1
instead, following jslint's advice.
As for why it is a better practice than ++
, according to Crockford:
The increment ++
and decrement --
operators make it possible to write in an extremely terse style. In languages such as C, they made it possible to write one-liners that: for (p = src, q = dest; !*p; p++, q++) *q = *p;
Most of the buffer overrun bugs that created terrible security vulnerabilities were due to code like this. In my own practice, I observed that when I used ++
and --
, my code tended to be too tight, too tricky, too cryptic. So, as a matter of discipline, I don’t use them any more.
Edit: Included comment from Nope as this answer continues to get views. Please continue to upvote his comment as well :)
To avoid confusion, and possible problems when using minifiers, always wrap parens around the operator and its operand when used together with the same (+ or -).
var i = 0, j = 0;alert(i++ +j);
This adds i and j (and increments i as a side effect) resulting in 0 being alerted.
But what is someone comes along and moves the space?
var i = 0, j = 0;alert(i+ ++j);
Now this first increments j, and then adds i to the new value of j, resulting in 1 being alerted.
This could easily be solved by doing
var i = 0, j = 0;alert((i++) +j);
Now this cannot be mistaken.