+ 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);
5 ответов
+ 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 😊
+ 1
@Chivas what do u mean ? 🤔
+ 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!
0
@chivas hahaha. I am not as good but still trying lol 😉
0
@Chivas ur xp is nearly 400 while mine is just 200 lol