Reputation: 3
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?
Upvotes: 0
Views: 118
Reputation: 11001
In sum += numbers[i]
, with operator +=
means sum = sum + numbers[i]
Upvotes: 0
Reputation: 941
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.
Upvotes: 2