If I recall correctly from Crockford’s “Javascript: The Good Parts”, he is not in favor of using the ++ or — operators, but I also tend to recall he doesn’t provide an especially strong argument against them.
Below is a use of these operators that I’ve found helpful in keeping my code as concise as possible particularly when dealing with functions/methods that return -1 when 0 is the first possible valid return value (along with positive integers). I’ll be interested in other atypical uses of ++ and/or — that make a strong argument in favor of using these operators when they make sense.
I do not consider this a duplicate of Why avoid increment ("++") and decrement ("–") operators in JavaScript? but rather it’s corollary: when to not avoid them, but rather use them to your advantage. Of course I could be mistaken and there could be some reason I’m not thinking of as to why the following is fraught with danger despite seeming to me to be elegant — if I’m missing something sub-optimal about the following, I’d like to know that too
var substrIdx = str.indexOf(substr);
if (++substrIdx) {
doSomething(--substrIdx);
}
It’s sub-optimal. It is confusing to humans, requires shipping more code over the browser, and requires the interpreter to do more work at runtime.
Someone trying to figure out what it is, has to reason about the state of
substrIdxat different points in the code — "it obeys the contract ofindexOfhere, but there it’s one greater than the contract ofindexOf, and after theifit doesn’t have a clear relationship tosubstr.".It’s also longer than
is harder for minifiers to minify because
substrIdxis no longer a single assignmentvar.A good minifier will turn the latter into something like
but fewer will do the job with the unnecessary assignment. They compare pretty well under closure compiler:
vs
because closure compiler misses the opportunity to turn
a>=0&&intoa<0||but the increment and decrement is still longer.