Why Avoid Increment (" ") and Decrement ("--") Operators in JavaScript?
While searching for ways to enhance JavaScript code, one may encounter suggestions to avoid the and -- operators. Like PHP's $foo[$bar ], these operators can lead to subtle off-by-one errors.
Alternative Control Flow
Consider the following loop constructs:
while( a < 10 ) do { /* foo */ a++; }
Or:
for (var i=0; i<10; i++) { /* foo */ }
Reasoning Behind Avoidance
The reason behind JSLint discouraging and -- boils down to two main rationales:
Recommended Usage
For optimal clarity, use and -- on separate lines, as exemplified below:
i++; array[i] = foo;
Instead of:
array[++i] = foo;
Exceptional Case: For Loops
For loops provide an exception to this rule. The and -- operators are commonly used in for loops, such as:
for (var j=0; j<10; j++) { console.log(j); }
In this context, the increment operator is considered idiomatic and serves a clear purpose.
The above is the detailed content of Why Should You Avoid Increment ( ) and Decrement (--) Operators in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!