187

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
}
brentonstrine
  • 21,694
  • 25
  • 74
  • 120
  • 5
    Cant you just substitute i = i + 3 for the third argument? Or is that only in Java? – CptJesus Oct 09 '12 at 23:18
  • 2
    Yes that's fine `i++` and `++i` are like `i+=1` if used in the for loop declaration so `i+=3` would work. – elclanrs Oct 09 '12 at 23:18
  • 1
    A `for` loop doesn't increment anything. Your code used in the `for` statement does. It's entirely up to you how/if/where/when you want to modify `i` or any other variable for that matter. – I Hate Lazy Oct 09 '12 at 23:24
  • 3
    That's not a for loop, it's an infinite loop. You mean `i+=3`. – ninjagecko Oct 09 '12 at 23:26
  • @user1689607 I should have said 'can a for loop be incremented'. Sorry for the poor grammar. – brentonstrine Oct 09 '12 at 23:39
  • @ninjagecko, only if `myVar.length` is infinite, right? And thanks, `=+` was what I was looking for. – brentonstrine Oct 09 '12 at 23:39
  • @brentonstrine: No, my point wasn't the grammer, but rather that your code can modify `i` in just the same way as you would in any other part of your code. – I Hate Lazy Oct 09 '12 at 23:40
  • @user1689607 Oh, gotcha. Thanks, I wasn't even thinking of putting it anywhere but the third expression. – brentonstrine Oct 09 '12 at 23:43
  • 3
    I get that this is a simple question with a simple solution, but what is the reason for the downvotes? I'm pretty sure it isn't a duplicate. – brentonstrine Oct 09 '12 at 23:46

9 Answers9

365

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.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • 1
    Thanks for the details--I was pretty sure there was a way to put more advanced expressions into the third slot--I had just forgotten that it needs to define the variable, so obviously `i+3` doesn't work. – brentonstrine Oct 09 '12 at 23:45
  • 2
    What is the cause of the endless loop when we do `i+3`? – Sanjay Shr Jun 03 '18 at 17:57
  • 2
    @SanjayShr `i+3` does not change the value of `i` – Nahid Jan 15 '19 at 01:16
  • @AndrewWhitaker Actually, the MDN article you linked to has _absolutely no example_ of incrementing other than the `i++` and `i--` simpletons as of today, which is a shame, since I thought only W3Schools stick to the essential for the simple minded. Hence the absolutely valid question here on SO. – Yin Cognyto Aug 04 '22 at 10:23
16

A for loop:

for(INIT; TEST; ADVANCE) {
    BODY
}

Means the following:

INIT;
while (true) {
    if (!TEST)
        break;
    BODY;
    ADVANCE;
}

You can write almost any expression for INIT, TEST, ADVANCE, and BODY.

Do note that the ++ operators and variants are operators with side-effects (one should try to avoid them if you are not using them like i+=1 and the like):

  • ++i means i+=1; return i
  • i++ means oldI=i; i+=1; return oldI

Example:

> i=0
> [i++, i, ++i, i, i--, i, --i, i]
[0, 1, 2, 2, 2, 1, 0, 0]
Adil Malik
  • 6,279
  • 7
  • 48
  • 77
ninjagecko
  • 88,546
  • 24
  • 137
  • 145
10
for (var i = 0; i < 10; i = i + 2) {
    // code here
}​
Barry
  • 3,303
  • 7
  • 23
  • 42
Adil Malik
  • 6,279
  • 7
  • 48
  • 77
5

Andrew Whitaker's answer is true, but you can use any expression for any part.
Just remember the second (middle) expression should evaluate so it can be compared to a boolean true or false.

When I use a for loop, I think of it as

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

as being

var i = 0;
while( i < 10 ) {
    /* expression */
    ++i;
}
Paul S.
  • 64,864
  • 9
  • 122
  • 138
4
for (var i = 0; i < myVar.length; i+=3) {
   //every three
}

additional

Operator   Example    Same As
  ++       X ++        x = x + 1
  --       X --        x = x - 1
  +=       x += y      x = x + y
  -=       x -= y      x = x - y
  *=       x *= y      x = x * y
  /=       x /= y      x = x / y
  %=       x %= y      x = x % y
Jayantha
  • 2,189
  • 1
  • 12
  • 13
2

You certainly can. Others have pointed out correctly that you need to do i += 3. You can't do what you have posted because all you are doing here is adding i + 3 but never assigning the result back to i. i++ is just a shorthand for i = i + 1, similarly i +=3 is a shorthand for i = i + 3.

2

For those who are looking to increment pair of numbers (like 1-2 to 3-4):

Solution one:

//initial values
var n_left = 1;
var n_right = 2;
    
for (i = 1; i <= 5; i++) {
        
    console.log(n_left + "-" + n_right);   
        
    n_left =+ n_left+2;
    n_right =+ n_right+2; 
}
//result: 1-2 3-4 5-6 7-8 9-10

Solution two:

for (x = 0; x <= 9; x+=2) {
    
    console.log((x+1) + "-" + (x+2));  

}
//result: 1-2 3-4 5-6 7-8 9-10
Fellipe Sanches
  • 7,395
  • 4
  • 32
  • 33
1

The last part of the ternary operator allows you to specify the increment step size. For instance, i++ means increment by 1. i+=2 is same as i=i+2,... etc. Example:

let val= [];

for (let i = 0; i < 9; i+=2) {
  val = val + i+",";
}


console.log(val);

Expected results: "2,4,6,8"

'i' can be any floating point or whole number depending on the desired step size.

Neville Lusimba
  • 827
  • 1
  • 8
  • 10
0

There is an operator just for this. For example, if I wanted to change a variable i by 3 then:

var someValue = 9;
var Increment  = 3;
for(var i=0;i<someValue;i+=Increment){
//do whatever
}
to decrease, you use -=
var someValue = 3;
var Increment  = 3;
for(var i=9;i>someValue;i+=Increment){
//do whatever
}