Can a for loop increment/decrement by more than one?

brentonstrine picture brentonstrine · Oct 10, 2012 · Viewed 269.9k times · Source

Are there other ways to increment a for loop in Javascript besides i++ and ++i? For example, I want to increment by 3 instead of one.

for (var i = 0; i < myVar.length; i+3) {
   //every three
}

Answer

Andrew Whitaker picture Andrew Whitaker · Oct 10, 2012

Use the += assignment operator:

for (var i = 0; i < myVar.length; i += 3) {

Technically, you can place any expression you'd like in the final expression of the for loop, but it is typically used to update the counter variable.

For more information about each step of the for loop, check out the MDN article.