Loop to add numbers in array JS | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Loop to add numbers in array JS

Hi coders, I was wondering how to create a loop that would log the sum of numbers in an array of numbers. First it would log index[0] but then on the second loop add index[0] + index[1] then index[0] + index[1] + index[2] and so on until the end of array. I’ve been trying to find a solution but nothing worked yet. Any ideas would be greatly appreciated, thanks :)

4th Jun 2018, 11:25 AM
Irena
Irena - avatar
4 Answers
+ 2
function addsum(arr){ var sum =0; for(var z =0;z<arr.length;z++){ sum+=arr[z]; } return sum; }
4th Jun 2018, 11:49 AM
Tomer Sim
Tomer Sim - avatar
+ 1
got it, I was so close to figure it out but I am already so overwhelmed from trying to figure out the infinite carousel thing with different image sizes that I simply couldn’t get it right lol. thank you guys :)
4th Jun 2018, 1:06 PM
Irena
Irena - avatar
+ 1
var arr = [1,2,3,4,34,24] var sum = 0; for(i=0;i<arr.length;i++){ sum += arr[i]; } console.log(sum);
4th Jun 2018, 4:59 PM
Shahriar Ahmad
Shahriar Ahmad - avatar
0
const arr = [1,2,3,4,34,24]; var sum = 0; let i =sum; for(i=0; i < arr.length; i++ ){ sum += arr[i] } console.log(sum);
22nd Sep 2023, 9:57 PM
Iyan