Skip to content Skip to sidebar Skip to footer

Other Ways To Increment A Variable In Javascript

Possible Duplicate: Why avoid increment (“++”) and decrement (“--”) operators in JavaScript? I'm a big fan of Douglas Crockford and his excellent book, JavaScript: The G

Solution 1:

I think this is rather controversial, and I personally stick to i++ in loops. Of cource, you can replace it with i = i + 1 in your loop statement, to be fully compliant to JSLint.

There aren't real alternatives to increment and decrement numerical values in JavaScript. You can often use Array.forEach() and/or Object.keys() in order to prevent numerical indexes.

Solution 2:

The only tricky thing I see in autoincrement/decrement operators (and I'm quite surprised that no one here pointed that out) is the difference between prefix (++i) and postfix (i++) versions. I also believe that autoincrement/decrement operators are slightly more efficient, in general. Besides this, I think the choice is based mainly on aesthetics, especially in javascript.

Solution 3:

to pass JSLint I now always do:

for (var i = 0; i < myArray.length; i+=1) { 
    // Loop Stuff 
}

Solution 4:

In C/C++ this is important, especially with arbitrary iterators and pre/post increment semantics. Also, random access vs forward-iterators.

In Javascript it's more about aesthetics than anything else. Unless you're dealing with strings. "1"+1 is "11".

I would say that ++i is an idiom that's worth being consistent with.

JSLint is wrong.

Solution 5:

Personally, I see nothing wrong with the ++/-- operators for incrementing and decrementing. While something like i = i + 1; may be easier for new coders, the practice is not rocket science once you know what the operators stand for.

Post a Comment for "Other Ways To Increment A Variable In Javascript"