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?

depperm
  • 8,490
  • 4
  • 37
  • 57
  • `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) – depperm Feb 26 '21 at 16:41
  • _“I read it as sum = 0+4”_ — How? Where does the `4` come from? Do you know [what `+=` does](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition_assignment)? Also see [How does += (plus equal) work?](https://stackoverflow.com/q/6826260/4642212). Or is it `numbers[i]` you’re having trouble with? See [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections). – Sebastian Simon Feb 26 '21 at 16:41
  • See [What does this symbol mean in JavaScript?](https://stackoverflow.com/q/9549780/4642212) and the documentation on MDN about [expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) and [statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements). – Sebastian Simon Feb 26 '21 at 16:41
  • number[i] I didn't understand. Thank you for the link. I will check it out. – George Munteanu Feb 26 '21 at 16:52

2 Answers2

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.

anpel
  • 877
  • 7
  • 15
  • 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 – George Munteanu Feb 26 '21 at 16:49
  • @GeorgeMunteanu No, you are not :) we all had to start somewhere, keep it up! – anpel Feb 26 '21 at 16:50
0

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

Siva K V
  • 7,622
  • 2
  • 11
  • 24