Abdoun abdou
Abdoun abdou

Reputation: 61

how i+=i works in a foor loop?

i wanted a for loop that sums a number 'i' with all previous numbers, for example : if i=5 then i want the loop to calculate the sum (5+4+3+2+1+0), then i tested this code which has returned some strange numbers:

//-----------i<5
for(i=0 ; i<5; i++){
  i += i;
}
console.log(i += i)

//---------i<6
for(i=0;i<6;i++){
  i += i;
}
console.log(i += i)

it had returned the same value for different 'i':

//for i <5
14
//for i < 6
14

Upvotes: 0

Views: 77

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36584

The problem is you are increasing i two times in a loop. One with i++ and second with i += i(meaning doubling i)

Now lets see how i changes in each iteration

i = 0;
//First iteration
i = 0(i += i)
i = 1(i++)
//Second iteration
i = 2(i += i)
i = 3(i++)
//Third
i = 6(i += i)
i++ (i = 7)

So the loop will exit because 7 > 5. So the last of i 7 in both the cases so it gives same value for both loops

Note: Don't ever assign variables to values like that. Always use keywords let(if you wanna change the variable afterwards). const(if you don't want to change variable afterwards). Also try to avoid var

Upvotes: 2

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6749

That's because they both stop when i reaches value of 7. Let's go over every single iteration, shall we?

During first iteration of the loop you:

  • start with i=0, then you add two zeros together with i+=i, and finally increase it by 1 via i++, you end up with i=1

During second iteration of the loop you:

  • start with i=1, they you add two 1s together with i+=i, and finally increase it by 1 via i++, you end up with i=3

During final iteration of the loop you:

  • start with i=3, they you add two 3s together with i+=i, and finally increase it by 1 via i++, you end up with i=7

Finally the console.log(i+=i) adds two 7s together and you get 14.

Both loops stop at the 3rd iteration when i reaches the value of 7

Upvotes: 3

Related Questions