+ 2

Could you Explain this code for me?

var arr = [2,4,6]; var x=1; for(var j=0; j<arr.length; j++){ x+=arr[j]; } alert(x); //output is 13

14th Aug 2019, 2:52 PM
Safaa Alnabhan
Safaa Alnabhan - avatar
5 Answers
+ 2
Safaa Alnabhan because the for-loop goes throw all elements of the array 'arr' and adds them to x
14th Aug 2019, 4:19 PM
Anton Böhler
Anton Böhler - avatar
+ 5
The code sums all items in the array plus 1, the initial value of x.
14th Aug 2019, 3:01 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 3
More descriptively, the program increases x by the sum of all elements of arr and alerts this final value of x, i.e., 1+2+4+6 = 13.
14th Aug 2019, 4:03 PM
Naveen Maurya
Naveen Maurya - avatar
+ 3
Its all derived from step-by-step analysis of the code. Try to run the code in your brain, logically deducing what the compiler/interpreter would have done. See, the for loop selects all the members of arr, one by one, and increments each value into x. That is it add all the elements to x one by one.
14th Aug 2019, 4:21 PM
Naveen Maurya
Naveen Maurya - avatar
+ 2
How did you know that we have to get the sum of all elements?
14th Aug 2019, 4:06 PM
Safaa Alnabhan
Safaa Alnabhan - avatar