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);
}
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 substrIdx
at different points in the code -- "it obeys the contract of indexOf
here, but there it's one greater than the contract of indexOf
, and after the if
it doesn't have a clear relationship to substr
.".
It's also longer than
var substrIdx = str.indexOf(substr);
if (substrIdx>=0) {
doSomething(substrIdx);
}
is harder for minifiers to minify because substrIdx
is no longer a single assignment var
.
A good minifier will turn the latter into something like
var substrIdx = str.indexOf(substr);
substrIdx<0||doSomething(substrIdx);
but fewer will do the job with the unnecessary assignment. They compare pretty well under closure compiler:
var a=str.indexOf(substr);++a&&doSomething(--a)
vs
var a=str.indexOf(substr);a>=0&&doSomething(a)
because closure compiler misses the opportunity to turn a>=0&&
into a<0||
but the increment and decrement is still longer.