Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atypical uses for Javascript's ++ and -- operators

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);
}
like image 988
Dexygen Avatar asked Dec 22 '22 06:12

Dexygen


1 Answers

Concise is not the same thing as readable or maintainable, and elegance is in the eye of the maintainer. The code you posted seems unnecessarily opaque to me.

Over the past couple of decades I have developed an intense aversion to code that isn't immediately obvious, even if the obvious method requires a good bit more code. Implicit and magic code is almost always less maintainable if more than one person is in the mix.

A specific comment: I don't see why you consider your code to be more concise, elegant, or readable than:

var substrIdx = str.indexOf(substr);
if (substrIdx >= 0) {
  doSomething(substrIdx);
}

It's also a tiny bit less efficient because you're performing two operations and a comparison instead of just a comparison. Additionally you're mistreating an integer as a boolean which is almost always a bad idea from a maintenance standpoint.

Finally as mentioned below you're hindering Javascript minimizers, and from a standpoint of conciseness at the end the only thing the user cares about is how quickly the page loads...

like image 113
Scott A Avatar answered Dec 23 '22 20:12

Scott A