Responsible JavaScript: Incrementing and Decrementing

One area of JavaScript which has gotten a lot of negative attention lately is the increment and decrement operators. To be clear, much (if not all) of this discussion can be traced back to JSLint’s intolerance of them.

To understand this completely, you need to understand that JSLint is a project of Doug Crockford, a well known JavaScript architect with a reputation for his strict coding standards. Naturally, all of his recommendations have made their way into JSLint, including the topic of today’s post.

An Extreme Example

The ++ (increment) and — (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. There is a plusplus option that prohibits the use of these operators.
Douglas Crockford

Those are some serious words, but Doug has a good point: If you aren’t careful, your code can get pretty messy with fancy expressions. For example, all of this is valid JavaScript:

var a = 1;
var b = 2;
var c = 3;

a++ + b;
a + ++b;
a + + + b;

console.log(a, b, c);

Its easy to look at an isolated example such as the one above and say “sure, but nobody writes code like that in real life.” Sorry, but you would be wrong. Just ask Google

The sad fact of the matter is that we all write code like that at some point. It looks like it’s alright when we write it, but then when it comes time to maintain it or hand it off to another developer for them to figure out.

The other side of the coin

While the above code is frightening, the reality is that there are much more common uses of the increment/decrement operators. In fact, for most people, their first experience with these operators is in the simple for loop.

for (var i = 0; i < foo.length; i++) {
    bar.doSomething(foo[i]);
}

While there may be better ways of iterating arrays, code like the above is so common that it’s instantly recognizable.

Another, quite common example is when concatenating numbers to strings in JavaScript. Consider the following snippet:

var grandTotal = myXmlDoc.getElementById('grand-total').nodeValue;
var statusMessage = 'Your card will be charged $'+ (+grandTotal).toFixed(2) + '.';

Since grandTotal ins’t a number, we need to convert it using the + operator. Unfortunately, that is also the concatenation operator which makes for an interesting mess of symbols.

There is an interesting thing to note here: the use of parenthesis. In this case, they are required, however in some of the more ambiguous situations (above) they can help clarify some complicated code.

There are plenty of other ways that incrementors and decrementors can be used safely. Yes, it is very possible to write bad code with these operators — and they certainly do make it much easier to make serious mistakes. However, instead of eliminating them entirely from your code, how about simply using some common sense? Simply put, there are just as many ways these operators can simplify your code as there are ways they can overcomplicate it.

Complex incrementing or decrementing operations (like all complex code) should be handled responsibly. Here are a few best practices to keep in mind:

  1. Move type conversions, long series of concatenations, and any other tricky code into a helper method.
  2. Know the difference between pre-incrementing and post-incrementing and use them appropriately.
  3. Really think before nesting incrementors or decrementors in expressions such as array key references or return values.

Related Links:

This entry was posted in Design Patterns, JavaScript. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>