artlung artlung - 1 year ago 73
Javascript Question

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

I'm a big fan of Douglas Crockford's writing on JavaScript, particularly his book JavaScript: The Good Parts. It's made me a better JavaScript programmer and a better programmer in general. One of his tips for his jslint tool is this :

++ and --

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

This has always struck my gut as "yes, that makes sense," but has annoyed me when I've needed a looping condition and can't figure out a better way to control the loop than a
while( a < 10 )do { a++ }
for (var i=0;i<10;i++) { }
and use jslint. It's challenged me to write it differently. I also know in the distant past using things, in say PHP like
has gotten me in trouble with off-by-one errors.

Are there C-like languages or other languages that lack the "
" and "
" syntax or handle it differently?

Are there other rationales for avoiding "
" and "
" that I might be missing?

UPDATE -- April 9, 2010:

In the video Crockford on JavaScript -- Part 5: The End of All Things, Douglas Crockford addresses the ++ issue more directly and with more detail. It appears at 1:09:00 in the timeline. Worth a watch.

UPDATE -- December 5, 2011:

Crockford again, from another excellent YUI Theater: Crockford on JavaScript - Section 8: Programming Style & Your Brain (50:42)

Answer Source

My view is to always use ++ and -- by themselves on a single line, as in:

array[i] = foo;

instead of

array[++i] = foo;

Anything beyond that can be confusing to some programmers and is just not worth it in my view. For loops are an exception, as the use of the increment operator is idiomatic and thus always clear.