DEV Community

yobra-king
yobra-king

Posted on

javascrip code not running

a = [3,26,46,74,86,83,84,84,74,74,74];
for(r = 0; r< 11; r = r + r){
sum = 0;
sum = sum + a[r];
};

Top comments (4)

Collapse
 
liftoffstudios profile image
Liftoff Studios • Edited

Hello
Please provide proper console output and format your code the next time you need help

Assuming you want the sum to come correctly, below is the correct code:

let a = [3,26,46,74,86,83,84,84,74,74,74];
let sum = 0;
for(var r = 0; r< 11; r = r + 1){
    sum = sum + a[r];
};
Enter fullscreen mode Exit fullscreen mode

Mistakes corrected in this version

  • You forgot to declare with let or var, not doing this makes the variable global
  • r=r+1 This is the correct way to do this r=r+r creates an infinite loop
  • sum variable had to be declared outside the for loop or else sum would always be the last number in the array

Hope this helped :)

Collapse
 
izio38 profile image
izio38

Hi, and welcome.

Community won't help you, if you don't provide console output at least.
With an explanation of what you are trying to do is better.

And last but not least, use code formatter, it's difficult to read currently.

We're humains on the other hands, show them some respect,

Have a nice day

Collapse
 
aarone4 profile image
Aaron Reese

1) what is your error message
2) you have not declared the variable r
3) you are setting r as a fixed value the same length as the array
4) you are incrementing r by itself so it is doubled on each iteration, but it starts at zero so will remain at zero and will run infinitely
5) you can do the required process using the reduce method on the array so a for loop is redundant

Collapse
 
kforp profile image
George Koval. • Edited
for (const r of a) {
  ...
}
Enter fullscreen mode Exit fullscreen mode

but the same can be achieved with reduce.

const sum = a.reduce((accumulator, current) => accumulator + current, 0);
Enter fullscreen mode Exit fullscreen mode