0

I'm following a coursera course and I'm a bit stuck on a line of code. I understand what it does but not why. The video explains how to get the avarage value of an Array.

I found this code online and its exactly the part that I don't get:

var numbers = [10, 20, 30, 40] // sums to 100
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
  sum += numbers[i]
}

I don't get this part:

sum+=numbers[i]

I read it as sum = 0+4.

What am I missing?

4
  • numbers is a list with values at indices. you reference the values with an index/indices using [], in this case i (which is 0, 1, 2, 3 - numbers.length is how many elements are in numbers) Commented Feb 26, 2021 at 16:41
  • “I read it as sum = 0+4” — How? Where does the 4 come from? Do you know what += does? Also see How does += (plus equal) work?. Or is it numbers[i] you’re having trouble with? See MDN. Commented Feb 26, 2021 at 16:41
  • See What does this symbol mean in JavaScript? and the documentation on MDN about expressions and operators and statements. Commented Feb 26, 2021 at 16:41
  • number[i] I didn't understand. Thank you for the link. I will check it out. Commented Feb 26, 2021 at 16:52

2 Answers 2

2

Basically what is says is "take whatever is in the i position of the numbers and add it to the value of sum".

So for example, if i = 2, then "whatever is in the i position of numbers would be 30.

To elaborate further, var numbers = [10, 20, 30, 40] can also be written as:

var numbers = [];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;

Hope this helps you understand better.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh! Ok I'mso dumb. I just couldn't understand of find anywhere what that i is supposed to do. I know you put the index number there usually. Thank you so much
@GeorgeMunteanu No, you are not :) we all had to start somewhere, keep it up!
0

In sum += numbers[i], with operator += means sum = sum + numbers[i]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.