Question about Iterate Through an Array with a For Loop

Tell us what’s happening:
I don’t understand why total += myArr[i] looks like,

var myArr = [ 2, 3, 4, 5, 6];
var total = 0
for (var i = 0; i < myArr.length; i++){
total += myArr[i] 
}
total + myArr[0] -> 0 + 2 = 2 
total + myArr[1] -> 2 + 3 = 5
total + myArr[2] -> 5 + 4 = 9
total + myArr[3] -> 9 + 5 = 14 
total + myArr[4] -> 14 + 6 = 20

but i have declared total = 0 already, why the total is not remain at 0?

Challenge: Iterate Through an Array with a For Loop

Link to the challenge:

@h0147xy
For example,
total += myArr[0] is like this total = total+myArr[0] which mean total, the variable, is equal to value of total which is 0 plus value of myArr[0]. So that’s
why the total increase.

  • total is a variable and = is the assignment operator
  • A variable, unless declared as a constant, can be assigned a new value.
  • The way assignment works is that the right side of = is first evaluated, then the evaluation outcome is assigned to the variable to the left of =.
  • total += myArr[i] is the same as total = total + myArr[i], and what this does is:
    • First, evaluate the right side of = by adding the value currently assigned to total and the value of myArr[i].
    • Then, assign the outcome of the above to the variable on the left side of = in this case total.

Make sure you understand this and have a consistent mental model of how assignment works as, according to some experienced programmers, it can largely predict whether you’ll be able to program or not.

Further reading:

oh i get it now, i thought total has been fixed at 0 constantly. Thank you for your explanation!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.