+ 3

js problem for loop

what is going on in this code explain me plz! for( var i=0; i<=8; i++){ i+=i console.log(i) } why result is 0 2 6 14

4th Jun 2019, 2:21 PM
Danielov
Danielov - avatar
3 Respostas
+ 1
i+=i => i+i, so the first number in the loop 0 +0 =0; the second 1+1=2; the third 3+3=6; the fourth 7+7=14; then the loop will stop cause the condition will be false that equal or less than 8;
4th Jun 2019, 2:36 PM
Shark
Shark - avatar
0
i += i is the short way of saying i = i + i (or, basically, multiply i by 2). First iteration: i = 0 i + i =0 Increase i by 1 Second iteration: i = 1 i + i = 2 Increase i by 1 Third iteration: i = 3 i + i = 6 Increase i by 1 Fourth: i = 7 i + i = 14 Stops because i is now greater than 8.
4th Jun 2019, 2:38 PM
Russ
Russ - avatar
0
~~ if you already know how loops work, skip this part ~~ First, the base, i = 0. Then you give a little if-statement for the increment/last part. i <=8 when i is smaller then or equal to 8, do the loop Lastly, the increment. i++ is used here. First it uses i, then it increments i (after the loop) if you loop (i=0; i<5; i++) you get 0 1 2 3 4, if you use (i=0; i<5; ++i) you get 1 2 3 4 Now that we know that, let's move to what's inside the loop ~~ end of the loop part, continue from here if you skipped ~~ Now inside the loop are two things, an increment of i (i+=i which is the same as i=i+i or i=2*i) So it doubles i and then it prints i in the console. Now for the loop it goes like this i=0 (first time) i+=i; i=0+0; i=0 console.log( 0 ) i++ (from the loop) i=1 i=1 (second) i+=i; i=1+1; i=2 console.log( 2 ) i++ (from the loop) i=3 i=3 (3th) i+=i; i=3+3; i=6 console.log( 6 ) i++ (from the loop) i=7 i=7; (4th and last) i=7+7; i=14 console.log( 14 ) i <= 8 is no longer true, therefor end output=(0 2 6 14)
4th Jun 2019, 2:46 PM
Roel
Roel - avatar