+ 1

I don't understand this exercise of javascript, help!

can someone explain to me why the output is equal to 6? var x=[1,2,4,1]; var sum=0; for (var i=0;i<x.length-1;i++) { sum+=x[i]; } document.write(sum);

21st Oct 2017, 7:35 PM
Angela_g710
Angela_g710 - avatar
5 Answers
+ 2
Hey Angela at first the output of this code is 7 not 6 and i will tell u why. variable sum is always 0 but sum+=x[i] is the same as sum = 0 + x[i] that means that sum = x[i] Cause adding 0 is nothing. now we have a loop that says that the first var i = 0 and it will keep increesing until i<x.length-1 now x.lenght-1 is the same as 3 that means that the loop will keep going until i=3 that means that we have x[0]+ x[1] + x[2] that gives us 1+2+4 that is 7 hope that i answered ur queation tell me if u dont understand and i will explain more šŸ˜Š
21st Oct 2017, 7:53 PM
Amr Aroub
Amr Aroub - avatar
+ 1
@Chivas what do u mean ? šŸ¤”
21st Oct 2017, 8:01 PM
Amr Aroub
Amr Aroub - avatar
+ 1
Yes, it's seven, I was wrong to write the question! thanks for your answers, did not know that the value of "sum" also changed! thanks!
21st Oct 2017, 9:49 PM
Angela_g710
Angela_g710 - avatar
0
@chivas hahaha. I am not as good but still trying lol šŸ˜‰
21st Oct 2017, 8:05 PM
Amr Aroub
Amr Aroub - avatar
0
@Chivas ur xp is nearly 400 while mine is just 200 lol
21st Oct 2017, 8:07 PM
Amr Aroub
Amr Aroub - avatar