Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

One of the tips for jslint tool is:

++ 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 operators.

I know that PHP constructs like $foo[$bar++] may easily result in off-by-one errors, but I couldn't figure out a better way to control the loop than a:

while( a < 10 ) do { /* foo */ a++; } 

or

for (var i=0; i<10; i++) { /* foo */ } 

Is the jslint highlighting them because there are some similar languages that lack the "++" and "--" syntax or handle it differently, or are there other rationales for avoiding "++" and "--" that I might be missing?

like image 648
artlung Avatar asked Jun 09 '09 17:06

artlung


People also ask

What will happen if you use increment and decrement operators on constant?

Increment operator increases the value of the variable by 1. Decrement operator decreases the value of the variable by 1.

Why do we prefer the prefix increment decrement operator?

Strongly favor the prefix version of the increment and decrement operators, as they are generally more performant, and you're less likely to run into strange issues with them. A function or expression is said to have a side effect if it does anything that persists beyond the life of the function or expression itself.

What is increment and decrement operators in JavaScript?

The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 . That is, it subtracts 1 from the value.


2 Answers

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

i++; 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.

like image 53
cdmckay Avatar answered Sep 18 '22 08:09

cdmckay


I'm frankly confused by that advice. Part of me wonders if it has more to do with a lack of experience (perceived or actual) with javascript coders.

I can see how someone just "hacking" away at some sample code could make an innocent mistake with ++ and --, but I don't see why an experienced professional would avoid them.

like image 30
Jon B Avatar answered Sep 22 '22 08:09

Jon B