+ 2

Could someone please explain me this code? This is javascript

var x = [1,2,4,1]; var sum = 0; for (var i=0 ; i<x.length-1; i++) { sum+= x[i] } document.write(sum);

8th Nov 2016, 3:54 AM
Andrés Amaya
Andrés Amaya - avatar
2 Answers
+ 4
at first we create an array x. then a variable which will store sum. now we run a loop that will fetch the elements of x the array and add to the sum. so in the loop I is started from 0 it will call x[0] that's the first element and add them next time second and as indexing starts from zero we end it arrays.length - one. and the program prints the sum of all elements of the array expect the last one. to calculate all condition should be x<array.length
8th Nov 2016, 4:04 AM
Sandeep Chatterjee
+ 3
It calculate the sum of all elements in the array x but the last element(1). Output --> 7<---1+2+4
8th Nov 2016, 4:57 AM
மனோஜ்குமார் பழனிச்சாமி
மனோஜ்குமார் பழனிச்சாமி - avatar